DEV Community

Koutaro Chikuba
Koutaro Chikuba

Posted on

Implement your GraphQL server on Firebase Function

Why

SPA and Mobile App need just one single endpoint to graphql.

This way can not implement subscription with ws backend. I think I don't need it because firestore will resolve it.

What I will not write in this article...

  • How to deploy to firebase
  • GraphQL Server implementation
  • webpack / npm install / package.json

functions code

functions/index.js

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)
Enter fullscreen mode Exit fullscreen mode

Send request to graphql

At first you need firebase deploy

Write your firebase.rules to proxy graphql endpoint

{
  "functions": {
    "source": "functions"
  },
  "hosting": {
    "rewrites": [
      {
        "source": "/api/graphql",
        "function": "graphql"
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Run firebase serve on your lacal and request query by apollo client.

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)
})

Enter fullscreen mode Exit fullscreen mode

CAUTION:2017/11/27 I have a problem about apollo-link so I add work arround to node_modules directly. https://github.com/apollographql/apollo-link/issues/248

Top comments (0)