Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
40
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@YutaroYoshikawa

FirestoreでGraphQLを使う

ポートフォリオのデータベースを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にする必要があります。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
40
Help us understand the problem. What are the problem?