Firebase & GraphQL

omgj picture omgj · May 31, 2016 · Viewed 33.4k times · Source

Does anyone have any experience with GraphQL and Firebase? I figure one would place the firebase calls in the resolver of the relevant field, passing some variable from the props of the component into the arguments of the query.

How can we insert new data in Firebase using GraphQL?

Answer

vince picture vince · Apr 24, 2017

To answer your question, there are three ways you can deal with this.

1. Firebase & GraphQL

If you're set on using Firebase, you can make a one-to-one mapping of Firebase's API into GraphQL queries and mutations.

You can surely wrap the Firebase API into GraphQL resolvers, and make calls that way. This is a good example of that:

const ref = path => firebase.database().ref(path)
const getValue = path => ref(path).once('value')
const mapSnapshotToEntities = snapshot => snapshot.val().map((value, id) => ({ id, ...value }))
const getEntities = path => getValue(path).then(mapSnapshotToEntities)

const resolvers = {
    Author: {
        posts(author) {
            return getEntities('posts').then(posts => filter(posts, { authorId: author.id }))
        },
    },

    Post: {
        author(post) {
            return getEntities('authors').then(posts => filter(authors, { id: authorId }))
        },
    },
};

Essentially, what you're doing here is using Firebase as a database, which works until you want to query your data in a relational manner in your resolvers. Without the ability to perform joins on the server side on top of your data store, you'll be making tons of round-trip requests to Firebase in your resolvers to fulfill just a single request.

The reason most people use Firebase is for its real-time capabilities, and not primarily just as a data store since the data relational modeling tools in this aspect are fairly lacking. With that, you're probably better off migrating over to GraphQL using a different data source.

2. GraphQL Backend as a Service

Considering you're open to using BaaS products like Firebase, you might consider switching over to a GraphQL BaaS.

3. Self-hosted GraphQL

If you're open to changing over to a self-hosted solution using your own data store, there are many benefits to that as well. Here are a few big hitters:

  • Flexibility of using your own data store and perhaps multiple to suit your specific app's needs

  • Custom queries and mutations

  • Natively add custom logic instead of via microservices attached to webhooks in your API

  • Roll your own authentication and permissioning mechanisms

  • Likely a lower-cost solution