DEV Community

roggc
roggc

Posted on

GraphQL and Firebase

In this post, I will explain to you how to implement a backend API with graphql which attacks a firebase database and to deploy it using firebase cloud functions.
The code will be in plain javascript and not ES6 to avoid adding more complexity with the babel stuff.
We start by creating a project folder. Name it api1 for example. Inside it, in the console or terminal, we run npm init -y to create package.json file. Then we run npm i firebase. After that we run npx firebase init functions. This will create a nested project inside api1 named functions.
After that, we create a folder named server under api1 root directory. In this folder, we will develop our backend API.
Our server will look like this:

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
var firebase =require('firebase/app');
require('firebase/database');

const firebaseConfig = {
  apiKey: "********",
  authDomain: "**********",
  databaseURL: "*********",
  projectId: "**********",
  storageBucket: "************",
  messagingSenderId: "**********",
  appId: "*************"
};

firebase.initializeApp(firebaseConfig);
var database = firebase.database();

const typeDefs = gql`
  type Query {
    hello: String
  }
  type Mutation{
    setName: Boolean
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello roger!',
  },
  Mutation:{
    setName:async()=>
    {
      await database.ref('users/').push({
        name: 'alejandro',
        surname: 'gomez gonzalez the best'
      })
      return true
    }
  }
};

function gqlServer() {
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    // Enable graphiql gui
    introspection: true,
    playground: true
  })

  const app = express()
  server.applyMiddleware({app, path: '/', cors: true})

  return app
}

module.exports = gqlServer
Enter fullscreen mode Exit fullscreen mode

This file is index1.js file under server folder under the root api1 folder.
Before editing this file what we do in the console of firebase is to register a new web app, named api1 or whatever you wish and copy the firebase configuration, and paste it into this file. This allows us to attack to the firebase database. See documentation in firebase for more detailed info on how to create a project and register a new web app.
The rest of the file is self-explanatory. We don't want here to explain graphql.
Also we must have had installed apollo-server-express and express in the outermost project, that is in the root directory.
Now, to test this implementation we do next file under same folder:

var gqlServer =require('./index1.js')

var server=gqlServer()
var port = process.env.PORT||5000

server.listen({port:port}, ()=>
  console.log(`🚀 Server ready at http://localhost:${port}`)
)
Enter fullscreen mode Exit fullscreen mode

We name it index.js. We run npx node server/index.js or write a script in package.json with "start":"node server/index.js" and run npm start. Then we go to localhost:5000 in the browser and test our API with the graphiql tool.
When we are happy with the API and we are done, we copy index1.js file into a server folder we create under functions directory. As I have said before this is another nested project. So what we do it is to change the directory in the console and go to functions directory and then install dependencies missing, which are firebase, apollo-server-express and express. We rename the file just copied to index.js.
In functions directory there will be a file named index.js (created when we executed at the beginning npx firebase init functions). This file will contain, excluding comments, this line of code:

const functions = require('firebase-functions');
Enter fullscreen mode Exit fullscreen mode

We add the next lines to the file:

const admin = require('firebase-admin');
const gqlServer=require('./server/index')

admin.initializeApp();

var server=gqlServer()

exports.api1=functions.https.onRequest(server)
Enter fullscreen mode Exit fullscreen mode

We are ready to go and deploy our firebase cloud function. We do npx firebase deploy --only functions. This will deploy our firebase cloud function and will give us in return a URL. We can get this URL going into functions section in firebase console.
We paste the URL into the browser and graphiql tool will appear. We must pay attention to add /api1 termination in the URL box inside graphiql tool itself and not the browser. It happens that while in the browser the URL is correct, in the graphiql tool the URL is missing this termination. So we add the termination and then test our API.
The final step is to test our API from a front end app.

Top comments (0)