Firebase云功能无法上传文件

时间:2018-10-11 11:55:13

标签: node.js firebase google-cloud-storage google-cloud-functions

我正在使用Firebase Cloud Functions创建和上传.csv报告。该文件未上传到gsc存储桶。我首先将.json转换为.csv,然后上传文件,然后将状态更改为“上传”,但是上传无法正常工作。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const fs = require('fs-extra');
const gcs = require('@google-cloud/storage');

const path = require('path');
const os = require('os');

const json2csv = require('json2csv');



exports.createCSV = functions.firestore
  .document('reports/{reportId}')
  .onCreate(event => {

    // Step 1. Set main variables

    const reportId = event.params.reportId;
    const fileName = `reports/${reportId}.csv`;
    const tempFilePath = path.join(os.tmpdir(), fileName);

    // Reference report in Firestore
    const db = admin.firestore();
    const reportRef = db.collection('reports').doc(reportId);

    // Reference Storage Bucket
    const storage = gcs.bucket('my-bucket-url'); // or set to env variable


    // Step 2. Query collection
    return db.collection('subscription_list')
      .get()
      .then(querySnapshot => {

        /// Step 3. Creates CSV file from with orders collection
        const orders = [];

        // create array of order data
        querySnapshot.forEach(doc => {
          orders.push( doc.data() )
        });


        return json2csv.parse({ data: orders });
      })
      .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: 'complete' })
      })
      .catch(err => console.log(err) )

  });

注意:首先要对安全规则进行身份验证。

我遇到的错误:

  

FirebaseStorageError。{code_:“存储/未找到对象”,消息_:“ Firebase存储:对象'reports / ByVUWzqI8igdUUWu2L82.csv'不存在。”,serverResponse_:“ {↵”错误“:{↵”代码”:404,↵“消息”:“未找到。无法获取对象“↵}↵}”,名称_:“ FirebaseError”}

0 个答案:

没有答案