There will be a focus on beautiful asynchronous code, which makes use of the async/await
feature in Node.js (available in v7.6 and above).
(Feel free to smile sweetly as you wave goodbye to callback hell
I’ll assume that you already have a Node.js application set up with the Firebase Admin SDK. If not, then check out the official setup guide.
First off, let’s create an example POST
endpoint which will save words to our Firebase Database instance:
// Dependencies
const admin = require('firebase-admin');
const express = require('express');
// Setup
const db = admin.database();
const router = express.Router();
// Middleware
router.use(bodyParser.json());
// API
router.post('/words', (req, res) => {
const {userId, word} = req.body;
db.ref(`words/${userId}`).push({word});
res.sendStatus(201);
});
firebase-write.js
This is a very basic endpoint which takes a userId
and a word
value, then saves the given word to a words
collection. Simple enough.
But something’s wrong. We’re missing error handling! In the example above, we return a 201
status code (meaning the resource was created), even if the word wasn’t properly saved to our Firebase Database instance.
So, let’s add some error handling:
// API
router.post('/words', (req, res) => {
const {userId, word} = req.body;
db.ref(`words/${userId}`).push({word}, error => {
if (error) {
res.sendStatus(500);
// Log error to external service, e.g. Sentry
} else {
res.sendStatus(201);
}
};
});
firebase-write-error-handling.js
Now that the endpoint returns accurate status codes, the client can display a relevant message to the user. For example, “Word saved successfully.” Or “Unable to save word, click here to try again.”
Note: if some of the ES2015+ syntax looks unfamiliar to you, check out the Babel ES2015 guide.### Reading data
OK, now that we’ve written some data to our Firebase Database, let’s try reading from it.
First, let’s see what a GET
endpoint looks like using the original promise-based method:
// API
router.get('/words', (req, res) => {
const {userId} = req.query;
db.ref(`words/${userId}`).once('value')
.then( snapshot => {
res.send(snapshot.val());
});
});
firebase-read-promise.js
Again, simple enough. Now let’s compare it with an async/await
version of the same code:
// API
router.get('/words', async (req, res) => {
const {userId} = req.query;
const wordsSnapshot = await db.ref(`words/${userId}`).once('value');
res.send(wordsSnapshot.val())
});
firebase-read.js
Note the async
keyword added before the function parameters (req, res)
and the await
keyword which now precedes the db.ref()
statement.
The db.ref()
method returns a promise, which means we can use the await
keyword to “pause” execution of the script. (The await
keyword can be used with any promise).
The final res.send()
method will only run after the db.ref()
promise is fulfilled.
That’s all well and good, but the true beauty of async/await
becomes apparent when you need to chain multiple asynchronous requests.
Let’s say you had to run a number of asynchronous functions sequentially:
const example = require('example-library');
example.firstAsyncRequest()
.then( fistResponse => {
example.secondAsyncRequest(fistResponse)
.then( secondResponse => {
example.thirdAsyncRequest(secondResponse)
.then( thirdAsyncResponse => {
// Insanity continues
});
});
});
promise-chain.js
Not pretty. This is also known as the “pyramid of doom” (and we haven’t even added error handlers yet).
Now take a look at the above snippet rewritten to use async/await
:
const example = require('example-library');
const runDemo = async () => {
const fistResponse = await example.firstAsyncRequest();
const secondResponse = await example.secondAsyncRequest(fistResponse);
const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
};
runDemo();
promise-chain-async.js
No more pyramid of doom! What’s more, all of the await
statements can be wrapped in a single try/catch
block to handle any errors:
const example = require('example-library');
const runDemo = async () => {
try {
const fistResponse = await example.firstAsyncRequest();
const secondResponse = await example.secondAsyncRequest(fistResponse);
const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
}
catch (error) {
// Handle error
}
};
runDemo();
promise-chain-async-error-handling.js
What about cases where you need to fetch multiple records from your Firebase Database at the same time?
Easy. Just use the Promise.all()
method to run Firebase Database requests in parallel:
// API
router.get('/words', async (req, res) => {
const wordsRef = db.ref(`words`).once('value');
const usersRef = db.ref(`users`).once('value');
const values = await Promise.all([wordsRef, usersRef]);
const wordsVal = values[0].val();
const userVal = values[1].val();
res.sendStatus(200);
});
parallel-async-await.js
When creating an endpoint to return data retrieved from a Firebase Database instance, be careful not to simply return the entire snapshot.val()
. This can cause an issue with JSON parsing on the client.
For example, say your client has the following code:
fetch('https://your-domain.com/api/words')
.then( response => response.json())
.then( json => {
// Handle data
})
.catch( error => {
// Error handling
});
client-read.js
The snapshot.val()
returned by Firebase can either be a JSON object, or null
if no record exists. If null
is returned, the response.json()
in the above snippet will throw an error, as it’s attempting to parse a non-object type.
To protect yourself from this, you can use Object.assign()
to always return an object to the client:
// API
router.get('/words', async (req, res) => {
const {userId} = req.query;
const wordsSnapshot = await db.ref(`words/${userId}`).once('value');
// BAD
res.send(wordsSnapshot.val())
// GOOD
const response = Object.assign({}, snapshot.val());
res.send(response);
});
firebase-snapshot.js
Thanks for reading!
Recommended Courses:
☞ Supreme NodeJS Course - For Beginners
☞ Learn Web Scraping with NodeJs in 2019 - The Crash Course
☞ NodeJS & MEAN Stack - for Beginners - In Easy way!
☞ End-to-End with Ionic4 & Parse/MongoDB on NodeJS/Express
☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)
#node-js