기본 콘텐츠로 건너뛰기

firebase /w functions + graphQL backend 만들기

persistence 영역을 graphQL 로 일반화 하고 apollo engine 같은 cache를 사용하고 싶다.

firebase의 functions를 통해 firebase를 불러오는 건 사실상 이중 작업인 것 같지만 apollo engine이 매우 맘에 들어 끌어들이고 싶다.

먼저 해볼 것은 functions에 graphql을 집어넣고 정적데이터를 읽어오는 것 먼저 로컬에서 구현해본다.

프로젝트 폴더를 생성하고

firebase init functions 부터 하자.
프로젝트를 선택(혹은 생성하고
? What language would you like to use to write Cloud Functions? JavaScript
✔  Wrote functions/package.json
✔  Wrote functions/index.js
그냥 firebase init 하고 functions를 선택하는 것과는 달리 뭔가 기본 scaffold를 생성해줘서 좋다.
{
  "functions": {
    "source": "functions"
  }
}
디폴트로 이렇게 해주자.

index.coffee 로 get 테스트.
exports하는 놈 이름이 functions 이름이 되고 경로도 /[exports한 놈]/ 이 되는 점이 특징이다.
functions = require 'firebase-functions'
admin = require 'firebase-admin'
admin.initializeApp functions.config().firebase
exports.addMessage = functions.https.onRequest (req, res)->
  original = req.query.text?
  admin.firestore()
    .collection 'messages'
    .add { original }
    .then (writeResult)->
      res.json result: "#{req.query.text} #{writeResult.id} added"
왜때문인지 모르겠는데 firebase serve --only functions 했을 떄 잘 작동하지 않는다.
firebase deploy --only functions 해주자.
$ curl https://us-central1-xxxxx.cloudfunctions.net/addMessage\?text\=mama
{"result":"mama u3rEkSMGDunsdqBpbX2g added"}%
잘 되는 것 같다.
db는 firebase가 아니라 firestore(beta)로 했다.
당연한 이야기지만
functions = require 'firebase-functions'
exports.addMessage = functions.https.onRequest (req, res)->
  original = req.query.text or ''
  res.json result: "#{original} entered"
이런 것도 잘된다.
그럼 일단 apollo server를 끼얹어 보자. functions 디렉토리 아래에서 
npm install --save apollo-server-express graphql-tools graphql express body-parser
패키지를 설치하고
express 먼저 테스트 해보자. functions이름은 api. 즉 /api 로 접근하게 하자.
functions = require 'firebase-functions'
express = require 'express'
app = express()
app.get '*', (req, res)->
  res.send "Hello express!"
exports.api = functions.https.onRequest app
간단히 될거라 생각했으나. 안된다.
curl https://us-central1-xxxxx.cloudfunctions.net/api

Cannot GET null
오류가 난다. 나만 그런건 아니었구나.
curl https://us-central1-xxxxx.cloudfunctions.net/api/
이처럼 /를 추가하니까 작동하는데 /api 가 root가 되서 그런 것 같다.

뭐 실제론 별 문제 아니니 https://www.apollographql.com/docs/apollo-server/example.html 보고 구현해보자.
주의할 점은 web frontend인 /graphiql이 바라보는 endpoint는 /graphql 이 아니라 /api/graphql 이 되는 점만 주의하면 된다.
functions = require 'firebase-functions'
express = require 'express'
bodyParser = require 'body-parser'
{ graphqlExpress, graphiqlExpress } = require 'apollo-server-express'
{ makeExecutableSchema } = require 'graphql-tools'
# fixture
books = [
    title: "Harry Potter and the Sorcerer's stone",
    author: 'J.K. Rowling'
  ,
    title: 'Jurassic Park',
    author: 'Michael Crichton'
]
typeDefs = """
  type Query { books: [Book] }
  type Book { title: String, author: String }
"""
resolvers =
  Query:
    books: => books
schema = makeExecutableSchema { typeDefs, resolvers }
app = express()
# /api/graphql
app.use '/graphql',
  bodyParser.json()
  graphqlExpress { schema, context: {} }
# /api/graphiql
app.use '/graphiql',
  graphiqlExpress endpointURL: '/api/graphql'
exports.api = functions.https.onRequest app
deploy 하고 graphiql을 열어보자.
브라우저에서 https://us-central1-xxxxx.cloudfunctions.net/api/graphiql 로 접근하면

짜자자장!

아하하. 멋져멋져. 박수짝짝.
조금 쉬었다가 apollo engine이나 firebase 연결 같은 걸 시도해봐야겠다.

댓글

이 블로그의 인기 게시물

세상 간단한 https(+secured websocket): Caddy

nginx, apache2 같은 걸로 매번 certbot 연동을 통해 https 하는게 지겨워서 알아보니 Caddy라는게 있더라. 설치법은 강하게 크기 위해 알아서 해본다. # cat /etc/caddy/Caddyfile your.shitty.site:8123 {   proxy / localhost:9123 {     websocket     transparent   } } 이건 외부에서 8123으로 들어오는 걸 내부적으로 9123로 맞춰서 https 맞춰주는 reverse proxy. 만일 port를 생략하면 # cat /etc/caddy/Caddyfile your.shitty.site {   proxy / localhost:9123 {     websocket     transparent   } } 기본포트인 443으로 되어 https://your.shitty.site 로 접속이 된다. 요새 말썽이던 cloudflare 버리고 netlify domain이랑 caddy를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

LG G Pro 2 Custom Rom +Rooting 기록

선 루팅 https://forum.xda-developers.com/lg-g3/general/guide-root-lg-firmwares-kitkat-lollipop-t3056951 1.2버전 스크립트 모드로. echo Looking for LG serial port.. echo. adb.exe wait-for-device 여기에서 정체 상태여서 강제로 adb kill-server 했더니 알아서 재부팅하심. 폰에선 "펌웨어 업데이트"화면이 나오고 Phone found at COM5! Rooting phone.. If you don't see the SuperSu installer script runs within about a minute, then the root failed. Author : blog.lvu.kr SPECIAL COMMAND : ENTER, LEAVE ## 이런 상황이 됨. #이 느린 속도로 하나씩 증가하고 있음. 한 시간 기다려도 성과없음. 뭐 몇번해봐도 안되고 결국 불안하긴 하지만 kingroot.net  로 설치 롤리팝이니까  https://drive.google.com/file/d/0B4kfGU1z_PClQ3AyM2lKOGR1S3M/view  이걸 받아서 압축 풀기. d838recovery.bat 만 있어서 당황스럽긴한데 실행하고 1번 하니까 리커버리 모드 진입까진 잘 되는 듯. adb sideload 라는게 있어서 해봄. Advance에서 adb sideload 선택하고 USB연결한 PC에서 adb sideload RR-N-v5.8.5-20171010-d838-Final.zip 하니까 착착 잘 진행됨. 이제 흉측한 U+LTE 가 없어짐. ㅇㅋ 군더더기 없고 깔끔한데 남은 건 gapps 를 설치해야함. http://opengapps.org/  를 권해줘서 갔는데 지옥 느림. ARM + 7.1 + stock 이 기본이...

Google Daydream 소감

드디어 V30 사은품인 Daydream이 왔다. 낭랑한 벨과 함께 무심한 듯 시크하게 툭 던지고 가시는 택배느님. 수령까지 두달 걸렸다. 눈을 뜨고 꿈꿔 보세요. 여기가 눈감으면 코베어 간다는 서울인가? 주황색면으로 열면 된다. 컨트롤러의 만듦새는 아주 좋다. 기존에 나와있는 사진엔 가로 머리끈만 있어서 똥머리한 언니들도 막 쓰고 플레이하고 그랬는데 실제로 보니 이중 끈이었다. 보통 돌아다니는 착샷 Daydream 설치 - 실행 - 폰 장착 - 컨트롤러 페어링 - VR진입까지 과정을 쉽게 하려고한 노력이 보였음. NFC로 데이드림뷰어에 폰을 장착하면 자동으로 인식하여 데이드림 앱이 실행되는 경험은 꽤 괜찮았음. 컨트롤러는 크기, 그립감 면에서 매우 훌륭하고 인식률, 반응속도 모두 만족스러움. 홈버튼으로 시선을 재 조정하는 발상은 좋은데 왼쪽 오른쪽이 앱마다 조금 혼란스럽고 상하방향 캘리브레이션은 안된다. 이 부분에서 좌절했다. 누워서 넷플릭스를 보는 건 다른 방법을 찾아보아야한다는 소리. 알고보니 이런 건 Youtube이나 Netflix, Skybox player 등등에서 테스트해본 결과 자체 앱에서 지원하고 있다. Netflix는 void theater라는 것이 있는데  <출처:  https://元ボクサーの一念発起.com/2018/05/10/oculus-go/ > Netflix app에서 요렇게 눈송이 같이 생긴 아이콘을 컨트롤러로 찍고 들어가면 화면만 덩그러니 나오고 스티어링휠(자동차 핸들) 모양 아이콘을 선택하고 누으면 자연스럽게 조정이 되었다. Youtube나 Skybox앱의 경우 아예 컨트롤러에서 꾹 누르고 화면 이동하는게 가능해서 편리. 게임은 이것저것 해봤는데 Rez Infinite이 최고. 아니 이건 그냥 전 VR 기기를 통틀어서 Rez Infinite이 최고가 아닐까 싶음;;; 결론,  1. 누워서 보기 잘된다. 2. ...