Skip to content

Instantly share code, notes, and snippets.

@tohagan
Forked from shangyilim/csv-cloud-function.js
Created November 12, 2022 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tohagan/9ef7a9d49a685680c0e10abb2ff8507b to your computer and use it in GitHub Desktop.
Save tohagan/9ef7a9d49a685680c0e10abb2ff8507b to your computer and use it in GitHub Desktop.
import * as functions from "firebase-functions";
import * as firebase from "firebase-admin";
import { parseAsync } from 'json2csv';
import { v4 as uuidv4 } from 'uuid';
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
firebase.initializeApp({
storageBucket: 'storage-bucket-name',
});
export const generateApplicationCsv = functions.region('asia-northeast1').pubsub
.topic("generate-application-csv")
.onPublish(async message => {
// gets the documents from the firestore collection
const applicationsSnapshot = await firebase
.firestore()
.collection("applications")
.get();
const applications = applicationsSnapshot.docs.map(doc => doc.data());
// csv field headers
const fields = [
'firstName',
'lastName',
];
// get csv output
const output = await parseAsync(applications, { fields });
// generate filename
const dateTime = new Date().toISOString().replace(/\W/g, "");
const filename = `applications_${dateTime}.csv`;
const tempLocalFile = path.join(os.tmpdir(), filename);
return new Promise((resolve, reject) => {
//write contents of csv into the temp file
fs.writeFile(tempLocalFile, output, error => {
if (error) {
reject(error);
return;
}
const bucket = firebase.storage().bucket();
// upload the file into the current firebase project default bucket
bucket
.upload(tempLocalFile, {
// Workaround: firebase console not generating token for files
// uploaded via Firebase Admin SDK
// https://github.com/firebase/firebase-admin-node/issues/694
metadata: {
metadata: {
firebaseStorageDownloadTokens: uuidv4(),
}
},
})
.then(() => resolve())
.catch(errorr => reject(errorr));
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment