Automation & Real-time Report Publishing with Google Firestore Function, Export Firestore data to CSV

Sunil Kumar
Nov 18, 2017 · 2 min read
npm install json2csv --savenpm i os --savenpm install --save pathnpm install fs-extranpm i @google-cloud/storage
const functions = require(‘firebase-functions’);const admin = require(‘firebase-admin’);admin.initializeApp(functions.config().firebase);const filesysRef = require(‘fs-extra’) //fs-extra adds file system methods that aren’t included in the native fs module and adds promise support to the fs methods.const storageRef = require(‘@google-cloud/storage’)(); //Using the Cloud Storage API module.const path = require(‘path’); //This is an exact copy of the NodeJS ’path’ module published to the NPM registry.const os = require(‘os’); //The os module provides a number of operating system-related utility methods.const j2c = require(‘json2csv’); //Converts json into csv with column titles and proper line endings.exports.exportReport = functions.firestore
.document(‘mysummary/{rptid}’)
.onCreate(event => {

const db = admin.firestore()
const myReport = event.params.rptid;
const fileName = `summary/${myReport}.csv`;
const tmpPath = path.join(os.tmpdir(), fileName);
const myreportRef = db.collection(‘summary’).doc(myReport)
const storageRef = storageRef.bucket(‘ADD_YOUR_BUCKET_URL_FROM_PROJECT_SETTINGS_CONSOLE’)

return db.collection(‘mysales’)
.get()
.then(querySnapshot => {
const sales = []
querySnapshot.forEach(doc => {
sales.push( doc.data() )
});

return j2c({ data: sales });
})
.then(csv => {
return filesysRef.outputFile(tmpPath, csv);
})
.then(() => {
return storageRef.upload(tmpPath, { reportlocation: fileName })
})
.catch(err => console.log(err) )
})

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Sunil Kumar

Written by

Angular, Ionic, Capacitor Developer, WordPress WooCommerce, Google Firestore and Cloud Function Expert

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.