Last active
November 12, 2022 08:36
-
-
Save shangyilim/77d52e3af635f97e8a0b71fd14a5625f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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