기본 콘텐츠로 건너뛰기

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를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

저지연 오디오 생성 LLVC 사용기

https://github.com/KoeAI/LLVC 써봄 CUDA 11.8 버전 쓰고 있어 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 VC 없어서 설치 https://wikidocs.net/168848 참조 FAIRSEQ 관련 오류 https://github.com/facebookresearch/fairseq/issues/2908 pip install editdistance  설치 No CUDA runtime is found, using CUDA_HOME='C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8' 오류 멀쩡하게 있는데 안됨. pip install torch==2.1.0+cu118 torchvision==0.16.0+cu118 torchaudio==2.1.0+cu118 --extra-index-url https://download.pytorch.org/whl/cu118 다시 설치 set DISTUTILS_USE_SDK=1 이게 문젠가 설정하고 재도전 Using cached ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl (118 kB) Building wheels for collected packages: fairseq   Building wheel for fairseq (pyproject.toml) ... error   error: subprocess-exited-with-error   × Building wheel for fairseq (pyproject.toml) did not run successfully.   │ exit code: 1   ╰─> [1829 lines of output]       No CUDA runtime is found, usi...