Last active
August 10, 2020 23:40
-
-
Save luke-lewandowski/7573a21fb795b1c970aaca509feb062e to your computer and use it in GitHub Desktop.
How to export Firestore to CSV
This file contains hidden or 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
| // By Felipe Gómez Restrepo | |
| export const createCSV = functions.firestore | |
| .document('reports/{reportId}') | |
| .onCreate((snap, context) => { | |
| // Step 1. Set main variables | |
| const reportId = context.params.reportId; | |
| const fileName = reports/${reportId}.csv; | |
| const tempFilePath = path.join(os.tmpdir(), fileName); | |
| const fields = ['id', 'nombre', 'telefono', 'fechacreacion', 'enviada', 'pregunta1', 'pregunta2', 'pregunta3', 'observacion1', 'observacion2', 'observacion3']; | |
| const opts = { fields }; | |
| // Reference report in Firestore | |
| const reportRef = db.collection('reports').doc(reportId) | |
| // Reference Storage Bucket | |
| const storage = gcs.bucket('') // or set to env variable | |
| // Instanciamiento objeto tipo Parser | |
| const parser = new Parser(opts); | |
| // Step 2. Query collection | |
| return db.collection('users') | |
| .get() | |
| .then(querySnapshot => { | |
| /// Step 3. Creates CSV file from with orders collection | |
| const users: any[] = [] | |
| // create array of users | |
| querySnapshot.forEach(doc => { | |
| doc | |
| users.push( doc.data() ) | |
| }); | |
| // return parser.parse({ data: users }); | |
| return parser.parse(users); | |
| }) | |
| .then(csv => { | |
| // Step 4. Write the file to cloud function tmp storage | |
| return fs.outputFile(tempFilePath, csv); | |
| }) | |
| .then(() => { | |
| // Step 5. Upload the file to Firebase cloud storage | |
| return storage.upload(tempFilePath, { destination: fileName }) | |
| }) | |
| .then(file => { | |
| // Step 6. Update status to complete in Firestore | |
| return reportRef.update({ status: 'completado' }) | |
| }) | |
| .catch(err => console.log(err) ) | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment