Last active
March 3, 2021 23:00
-
-
Save brygrill/287debab77de55790fab37c77580d6e4 to your computer and use it in GitHub Desktop.
Deploying a GraphQL Server with Firebase Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sample graphql server deployed with firebase functions | |
// pulling some basic stockmarket data from a firebase db | |
const functions = require('firebase-functions'); | |
const admin = require('firebase-admin'); | |
const express = require('express'); | |
const graphqlHTTP = require('express-graphql'); | |
const values = require('lodash.values'); | |
const { GraphQLSchema, GraphQLObjectType, GraphQLList, GraphQLString } = require('graphql'); | |
// Init express | |
const app = express(); | |
// Init Firebase admin | |
admin.initializeApp(functions.config().firebase); | |
// connect to db | |
const db = admin.database(); | |
const ref = db.ref('poll'); | |
// Construct Securities Type | |
const SecurityType = new GraphQLObjectType({ | |
name: 'Security', | |
description: 'A stock market security', | |
fields: () => ({ | |
symbol: { type: GraphQLString }, | |
name: { type: GraphQLString }, | |
open: { type: GraphQLString }, | |
last: { type: GraphQLString }, | |
percDay: { type: GraphQLString }, | |
status: { type: GraphQLString }, | |
volume: { type: GraphQLString }, | |
lastUpdatedAt: { type: GraphQLString }, | |
}), | |
}); | |
// Construct root query | |
const query = new GraphQLObjectType({ | |
name: 'Query', | |
description: 'The Root Query', | |
fields: () => ({ | |
securities: { | |
type: new GraphQLList(SecurityType), | |
description: 'A list of all securities', | |
resolve() { | |
return ref.child('securities').once('value').then(data => { | |
return values(data.val()); | |
}); | |
}, | |
}, | |
}), | |
}); | |
// Construct the schema | |
const schema = new GraphQLSchema({ | |
query, | |
}); | |
app.use('/', graphqlHTTP({ | |
schema, | |
graphiql: true, | |
})); | |
exports.graphql = functions.https.onRequest(app); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know you've uploaded this a long time ago but I'm trying to use this now and get an error. If you've ever encountered this I'd love to hear how you worked around it.