If you’ve used Firebase you know that one of the cooler aspects is watching the realtime database do its thing live right in front of you. As you watch your code execute, you’ll see it flash green as it adds new fields, yellow for changed nodes, and red for deletions. If you have a multi-path update in the database it goes without saying that you’ll see the colors popping up all over the place.

Then one day another one of your co-workers will say, “hey, I finally uploaded all of that data you asked for”. You go to the console, and you see at the top:

Read-only & non-realtime mode activated to improve browser performance

Select a key with fewer records to edit or view in realtime

What? No, my colors. My realtime updates. I have to drill down into a smaller subset of data to see that in action? Firebase, I get you don’t want to burn my battery and grind my browser to a halt, but what about my multi-path updates? It would be nice to see them all executing on the same screen. I could go into each node and look at them individually, but would I really be seeing what I need to see?

Well, using Node.js and the Firebase Tools there is a nice solution. Let’s just generate a small random subset of data, and upload that to the database. I assume that you already are familiar with Node.js and have it installed on your machine.

First, let’s tackle generating some random data. There are quite a few libraries and tools out there. I tried JSON Schema Faker and a couple others but those didn’t work out to well because of Firebase’s peculiar structure and how random keys are generated for a JSON object. So I decided to go with Chance to generate some random variables, and I was happy with the results. Chance let’s you generate random data such as names, UUIDs, etc.

const item = {}
item.uid = chance.guid();
item.email = chance.email();
item.profileImageUrl = chance.avatar();
item.username = chance.name();

This creates some random user information. We can take this a step further by creating a function that will generate a random number of these items, in this case users.

function randomIntInc(low, high) {
    return Math.floor(Math.random() * (high - low + 1) + low);
}

function createUsers(low, high) {
    let items = {};

    const generatedItems = randomIntInc(low, high);
    for (let i = 0; i < generatedItems; i++) {
        const item = {}
        item.uid = chance.guid();
        ...

        const parent = {}
        parent[item.uid] = item
        Object.assign(items, parent)
    }

    return items;
}

Our export function is super simple since we just want to generate a set of random users.

exports.schema = function () {
    let parent = {}
    parent.users = createUsers(3, 7);
    return parent;
}

The create users call will generate any number of users between 3 and 7, you can adjust the numbers to fit your needs. Next, we have a separate module that will import this file, generate the JSON data, and save the file to disk.

const json = mockDataSchema.schema();
const jsonFormatted = JSON.stringify(json);

fs.writeFile("./mockData/db.json", jsonFormatted, (err) => {
    if (err) {
        return console.log(chalk.red(err));
    } else {
        console.log(chalk.green("Mock data generated."));
    }
});

Now we can finally push it to Firebase. Make sure you have the Firebase Tools installed on your machine and type the command:

firebase database:set / ./mockData/db.json

WAIT!

Did you do it? Did you have the correct database? It wasn’t your production project was it? Did you just write over the entire production database? There has to be a safer way isn’t there?

Yes, there is. We can use the firebase tools in node.js as well. Let’s update our generateMockData.js file to use that, so we can have the dev or qa project always set. That way we will never accidentally overwrite our production database because we didn’t configure the firebase tools correctly. This is really easy to do.

const client = require('firebase-tools');
client.database.set('/', './mockData/db.json', {
  project: 'my-test-project',
  token: process.env.FIREBASE_TOKEN,
  cwd: './'
});

The first parameter is the path in the database. In this case / is the root of the database. The second parameter is the file, and the third are various options. Note: if you signed in using the firebase tools then the token isn’t necessary.

Finally, we can setup a custom npm script that we can call to take care of everything, on a non-production firebase project. So in our package.json we’ll just add a new script:

"generate-mock-data": "node generateMockData"

Then we call

npm run generate-mock-data

and we once again have realtime data in the firebase realtime database. Use this method to build small subsets of test data that you can quickly deploy to your Firebase instance for troubleshooting your Firebase functions, or any other issues you might be trying to debug. Happy coding!

You can find the code sample for this blog post here.

1 Comment