Using GraphQL to Query Your Firebase Realtime Database

Mehak Vohra
Jul 12 · 7 min read

By: Mehak Vohra

While working on a project, I wanted to use GraphQL to query my Firebase Realtime Database. After a few hours I finally figured it out, so I thought I’d share since there doesn’t seem to be much online about this.

This guide assumes you have a basic background in Node, GraphQL, Firebase, and using a CLI.

Table of Contents:
1.
Setting Up Your Firebase Project
2. Creating Your Server
3. Making Your Schema
4. Start Mapping Through Your JSON Object
5. Create Your Converting Function
6. Finish Mapping and Run

Setting Up Your Firebase Project

To get started, let’s set up your Firebase project. This is where you will house all of your data for your web app.

Create a Firebase Project and app.

Go to your Firebase Console and create a new project by clicking “+Add Project”.

Name your project and set your location.

After your new project is made, head over to the left sidebar, and click “Database”.

Within Database, scroll down, and select Create Database under Realtime Database.

You are then going to see a pop-up. Select test mode.

Awesome! You can now upload some data. Go ahead and use this JSON file if you want to follow along with the tutorial. Save this as data.json and upload it to your database by selecting the three dots in the top right corner, and importing the JSON.

{
"users": {
"01": {
"age": 22,
"citizen": true,
"email": "",
"fullName": "Mehak Vohra",
"location": "San Francisco, CA"
},
"02": {
"age": 27,
"citizen": true,
"email": "",
"fullName": "Andrew Linfoot",
"location": "Los Angeles, CA"
}
}
}

Your database should now look like this.

Now, we’re ready to move on to coding.

Creating Your Server

Let’s go ahead, and set up your GraphQL server.

Create a folder, and in your terminal initialize yarn.

$ yarn init

Your project will be broken down into 2 main folders.

  1. src: This is where your TypeDefs, Resolvers, and Server will live.
  2. FirebaseFunctions: This is where you write the functions to help map over your JSON objects so that you can query them.
Server Folder
|
|
FirebaseFunctions
|
userProfile.js
|
|
node_modules
|
|
src---
resolvers.js
|
server.js
|
typeDefs.js
|
|
.env
.package.json
yarn.lock

Next, we’re going to add in all of our dependencies to get started.

yarn add apollo-server apollo-server-express dotenv express firebase graphql

Your package.json file should look like this. I’ve altered our start script so that we can run our server easily when it’s done.

{"dependencies": {
"apollo-server": "^2.6.7",
"apollo-server-express": "^2.6.7",
"dotenv": "^8.0.0"
"express": "^4.17.1",
"firebase": "^6.2.4",
"graphql": "^14.4.2"
},
"scripts": {
"start": "node src/server.js",
"dev": "node server.js"
}
}

In your src folder. Create a new file called server.js

This will be the page where we create the GraphQL Server. First, we are going to import all of our dependencies.

const express = require("express");
const { ApolloServer } = require("apollo-server-express");
const firebase = require("firebase");
require("dotenv").config();

Second, we are going to create our express app.

const app = express();

Next, we are going to create two more files in the src folder. They are going to be called typeDefs.js and resolvers.js.

From there, we are going to import those files into the server.js file, and also create our Apollo server.

const typeDefs = require("./typeDefs");
const resolvers = require("./resolvers");
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
return {
headers: req.headers,
};
}
});
server.applyMiddleware({ app });app.listen({ port: 4000 }, () => {
console.log("Server has started 🚀 ");
});

Making Your Schema

Your schema will be created in the typeDefs.js file. This is where you tell GraphQL how you’d like to structure your information.

We are going to create a schema for a User, and also create the Query type for users, and export it out.

const { gql } = require("apollo-server");const typeDefs = gql`
type User {
fullName: String
email: String!
location: String
age: String
citizen: Boolean
}
type Query {
users: [User]
}
`;
module.exports = typeDefs;

Start Mapping Through Your JSON Object

Next up, let’s go back to your Firebase console.

Go to the top left corner in your Project and Click the gears > select Project Settings. Scroll down to the bottom, and create a web app (</>).

Name your app.

Go back to your settings console, and click the Config option under the Firebase SDK snippet.

Copy the apiKey, authDomain, databaseURL, and projectId information.

Then, go to your server.js and initialize the Firebase app. I’d suggest the information to a .env file, or if you’re feeling frisky, just go ahead and paste the information straight.

I put it right above the Apollo Server and then added it to the context for the server.

const firebaseClient = firebase.initializeApp({
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID
});
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
return {
headers: req.headers,
firebaseClient
};
}
});

Now, we are going to create a resolvers.js page in the src folder. This is how we tell GraphQL where it should be looking for information.

First, we are going to add in the database URL to make calls to the API. I’d suggest putting this in the .env file as well. You can find this in the information we just grabbed from the console.

const baseURL = process.env.FIREBASE_DATABASE_URL;

Second, we’re going to create the users Query. The code below makes a fetch call to the API and calls the users.json endpoint in the Realtime Database. We then turn that data into a JSON object. This makes it so that we can map through it.

In the Firebase Realtime Database, the way you access each user is through using Object.keys() function. So, we are going to split our data into 2 user objects.

Query: {
users: async () => {
const data = await fetch(`${baseURL}/users.json`);
const dataJson = await data.json();
const keys = Object.keys(dataJson);
}
}

Next up, we want to map through each user object and connect them to our schema.

Create Your Converting Function

In your FirebaseFunctions folder, create a file called userProfile.js. This is a function to show GraphQL what data they should be paying attention to.

As I’m creating functions like these, I always print the JSON object so that I can reference it as I build the function out.

If you were to console log dataJson, you would get this.

const dataJson = {
{ "01": {
age: 22,
citizen: true,
email: "",
ethnicity: "asian",
fullName: "Mehak",
gender: "female",
id: "fwjh43jf423f",
instagramUrl: "",
linkedInUrl: "",
location: "San Francisco, CA",
phoneNumber: "(304) 629-1985"
},
"02": {
age: 32,
citizen: true,
email: "",
ethnicity: "asian",
fullName: "Mehak",
gender: "male",
id: "wrth42j3h4f",
instagramUrl: "",
linkedInUrl: "",
location: "Los Angeles, CA",
phoneNumber: "(421) 000-0000"
}
}}

Now, let’s create our mapping function in userProfile.js. Each variable we mention here should already be in our schema. Create the function, and then export it.

function userProfile(data) {
return {
age: data.age,
citizen: data.citizen,
email: data.email,
fullName: data.fullName,
location: data.location
};
}
module.exports = userProfile;

Finish Mapping and Run

We are on the home stretch! Let’s go ahead and finish up our resolvers.json file. Before we move forward, import the function we just made to the top of the file.

const baseURL = process.env.FIREBASE_DATABASE_URL;

Now, we’re going to go over every item in our users Query in resolvers.json, and then use our new function to help us map the information. It will look like this.

const resolvers = {
Query: {
users: async () => {
const data = await fetch(`${baseURL}/users.json`);
const dataJson = await data.json();
const keys = Object.keys(dataJson);
const mapsKeys = keys.map(function(item) {
const userData = dataJson[item];
const graphqlUser = userProfile(userData);
return graphqlUser;
});
return mapsKeys;
}
}
};

Then, we’re going to export the resolvers at the bottom of the page.

module.exports = resolvers;

We’re done!

Now let’s start our server.

$ yarn start

You will see your GraphQL screen come up at your localhost URL. Type in a Query for users, and your server should work!

Congrats! You’re done! 🎉


If you have any questions, feel free to reach out. Hopefully, this helped!

Catch Me Online 💻

Mehak Vohra

A place for my musings and thoughts.

Mehak Vohra

Written by

CEO of OnDelta | On a mission to create the next generation of marketers.

Mehak Vohra

A place for my musings and thoughts.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade