Use A Javascript Class To Upload A Json File To Firebase Firestore

Here I wrote a simple class that will enable one to take a JSON file and upload its content to the Firebase Firestore database. The code is quite explanatory for itself. All you need is a firebase project. Get the credential from your project settings to give authorization for one to be able to write data to firebase.

1
2
3
4
5
6
7
8
// Initialize Firebase
// Get your firebase credentials from 
// the firebase console for your project
firebase.initializeApp({
  apiKey: [YOUR_FIREBASE_APIKEY],
  authDomain: [YOUR_FIREBASE_AUTHDOMAIN],
  projectId: [YOUR_FIREBASE_PROJECTID]
});

You don't need to know how to code to use this class. All it requires is a one Node Cli command.

1
RUN: node json-to-firestore/populateJsonFirestore.js [RELATIVE PATH TO FILE] [FIRESTORE METHOD] [COLLECTION NAME]

Here is the complete Js class to upload json to firebase:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
const fs = require('fs');
const { resolve } = require('path');
// Initialize Firebase
// Get your firebase credentials from 
// the firebase console for your project
firebase.initializeApp({
  apiKey: [YOUR_FIREBASE_APIKEY],
  authDomain: [YOUR_FIREBASE_AUTHDOMAIN],
  projectId: [YOUR_FIREBASE_PROJECTID]
});

/**
 * Tutorial on how to upload json data to firestore
 * Using JavaScript
 * RUN: node json-to-firestore/populateJsonFirestore.js [RELATIVE PATH TO FILE] [FIRESTORE METHOD] [COLLECTION NAME]
 */
class PopulateJsonFireStore {
  // class constructor
  constructor() {
    console.time("Time taken");
    this.db = firebase.firestore();
    // Obtain the relative path, method type, collection name arguments provided through
    const [, , filepath, type, collectionname] = process.argv;

    // Obtain the absolute path for the given relative
    this.absolutepath = resolve(process.cwd(), filepath);

    // Obtain the firestore method type
    this.type = type;

    // Obtain the firestore method type
    this.collectionname = collectionname;

    // Lets make sure the right firestore method is used.
    if (this.type !== 'set' && this.type !== 'add') {
      console.error(`Wrong method type ${this.type}`)
      console.log('Accepted methods are: set or add');
      this.exit(1);
    }

    // If file path is missing
    if (this.absolutepath == null || this.absolutepath.length < 1){
      console.error(`Make sure you have file path assigned ${this.absolutepath}`)
      this.exit(1);
    }

    // If collection name not set
    if (this.collectionname == null || this.collectionname.length < 1){
      console.error(`Make sure to specify firestore collection ${this.collectionname}`)
      this.exit(1);
    }


    console.log(`ABS: FILE PATH ${this.absolutepath}`);
    console.log(`Type: method is ${this.type}`);
  }



  // The populate function
  // uploads the json data to firestore
  async populate() {
    // initialize our data array
    let data = [];

    // Get data from json file using fs
    try {
      data = JSON.parse(fs.readFileSync(this.absolutepath, {}), 'utf8');
    } catch (e) {
      console.error(e.message);
    }

    //data.forEach((item) => console.log(item));
    // loop through the data
    // Populate Firestore on each run
    // Make sure file has atleast one item.
    if (data.length < 1) {
      console.error('Make sure file contains items.');
    }
    var i = 0;
    for (var item of data) {
      console.log(item);
      try {
        this.type === 'set' ? await this.set(item) : await this.add(item);
      } catch (e) {
        console.log(e.message)
        this.exit(1);
      }
      // Successfully got to end of data;
      // print success message
      if (data.length - 1 === i) {
        console.log(`**************************\n****SUCCESS UPLOAD*****\n**************************`);
        console.timeEnd("Time taken");
        this.exit(0);
      }

      i++;
    }

  }

  // Sets data to firestore database
  // Firestore auto generated IDS
  add(item) {
    console.log(`Adding item with id ${item.id}`);
    return this.db.collection(this.collectionname).add(Object.assign({}, item))
    .then(() => true)
    .catch((e) => console.error(e.message));
  }

  // Set data with specified ID
  // Custom Generated IDS
  set(item) {
    console.log(`setting item with id ${item.id}`);
    return this.db.doc(`${this.collectionname}/${item.id}`).set(Object.assign({}, item))
    .then(() => true)
    .catch((e) => console.error(e.message));
  }

  // Exit nodejs console
  exit(code) {
    return process.exit(code);
  }

}

// create instance of class
// Run populate function
const populateFireStore = new PopulateJsonFireStore();
populateFireStore.populate();

Code: https://github.com/ericel/tutoring/tree/main/javascript/json-to-firestore In this class, you have two alternative methods(add or set) to add your data to Firestore. The set method gives you the option of using custom ids for your content, while with the add method, firebase auto generates document ids for your content.

Related Posts

1 Comments

12345

  • Ericel123

    Ericel1231 week, 2 days ago

    no comments yet

    Helpful (1) Unhelpful (0)
01