在Firebase Functions上实现GraphQL服务器

这篇文章是关于我一个月后无法找到内容的情况,所以决定写一篇有关圣诞节降临的文章。

为什么?

我认为在 SPA 或移动应用中,首先使用 Firebase Functions 来挂载一个 GraphQL 终点,并通过付费来扩展,这是一个很好的起点。这就像使用金弹头一样。

这个环境可以实现查询和突变,但是由于云函数的生命周期的原因,无法实现ws后端订阅。这方面可以使用Firestore之类的来解决。

对于我的用途来说,我禁止使用Firestore的写入功能,使用firebase.rules来控制读取功能并进行订阅,将实时非复杂查询和带有逻辑验证的副作用转移到GraphQL中进行,这是我的设想。

这篇文章不会进行解释。

    • firebase にデプロイする手順

 

    • graphql スキーマ定義やリゾルバの実装方法

 

    webpack や npm install や package.json

功能定義

就这样。

const functions = require('firebase-functions')
const express = require('express')
const { graphqlExpress } = require('apollo-server-express')
const bodyParser = require('body-parser')
const { makeExecutableSchema } = require('graphql-tools')

const schema = makeExecutableSchema({
  typeDefs: [/* Your schema.graphql */],
  resolvers: {/* Your resolver */}
})

const server = express().use(
  bodyParser.json(),
  graphqlExpress({ schema, context: {} })
)

exports.graphql = functions.https.onRequest(server)

请自行查阅如何通过 makeExecutableSchema 实现 GraphQL 服务器。
链接地址:
https://github.com/apollographql/graphql-tools
https://github.com/mizchi-sandbox/play-graphql-server

将请求从客户端发送到GraphQL。

使用 firebase deploy 进行部署(缩写)

在Firebase的rewrite规则中指定GraphQL函数。

{
  "functions": {
    "source": "functions"
  },
  "hosting": {
    "rewrites": [
      {
        "source": "/api/graphql",
        "function": "graphql"
      }
    ]
  }
}

在Firebase中运行本地服务器,例如使用”firebase serve”命令。

从ApolloClient发出请求。

import 'isomorphic-fetch'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import gql from 'graphql-tag'

const client = new ApolloClient({
  link: new HttpLink({ uri: 'http://localhost:5000/api/graphql' }),
  cache: new InMemoryCache()
})

client.query({
  query: gql`<your query>`
}).then(ret => {
 console.log(ret)
})

注意:截至2017年11月27日,遇到了此构建错误,因此需要针对apollo-link的解决方法。参见https://github.com/apollographql/apollo-link/issues/248。

需要将以下内容用中文重新表达,只需给出一个选项:

待办事项

    • あとでサンプルプロジェクトを公開

 

    • Firebase Auth との認証系を作る

 

    認証トークンを使って Firestore を殴る
bannerAds