49
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ポートフォリオのデータベースをFirestoreで作っていて、クライアント側のリソース節約のためにGlaphQLの実装の仕方を調べたのでメモ。
ライブラリはapolloを使っていきます。

index.ts
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as serviceAccount from './service-account.json'
import { ApolloServer, gql } from 'apollo-server-cloud-functions'

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount as any)
})

const typeDefs = gql`
type Query {
  workses: [Works]
}
type Works {
  name: String!
  thumb: String!
}
`

interface Works {
  name: string
  thumb: string
}

const resolvers = {
  Query: {
    async workses() {
      const workses = await admin
        .firestore()
        .collection('works')
        .get()
      return workses.docs.map(works => works.data()) as Works[]
    }
  }
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req, res }) => ({
    headers: req.headers,
    req,
    res,
  }),
})

export const apollo = functions.https.onRequest(server.createHandler(
////必要であればcorsもオフにできる
//{
//  cors: {
//    origin: false
//  },
//}
))

Firebase Functionsに上記のように記述し、デプロイすればURLが発行されてそれがGraphQLエンドポイントになります。
ちなみに、jsonファイルを型付でインポートするにはtsconfigでresolveJsonModuleプロパティをtrueにする必要があります。

49
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?