Облачные функции Google Firebase - Скачать файл - Не найдено - PullRequest
0 голосов
/ 24 октября 2018

Я пытаюсь сделать пример с генератором большого пальца (генерировать миниатюру изображения при загрузке).Этот пример был адаптером от предыдущей версии API.

const functions = require('firebase-functions');
const { Storage } = require('@google-cloud/storage');
const os = require('os');
const path = require('path');
const sharp = require('sharp');
const fs = require('fs-extra');

exports.generateThumbs = functions.storage
  .object()
  .onFinalize(async (object) => {

    const storage = new Storage();
    const bucket = await storage.bucket(object.name);

    const filePath = object.name;
    const fileName = filePath.split('/').pop();
    const bucketDir = path.dirname(filePath);

    const workingDir = path.join(os.tmpdir(), 'thumbs');
    const tmpFilePath = path.join(workingDir, 'source.png');

    if (fileName.includes('thumb@') || !object.contentType.includes('image')) {
      console.log('exiting function');
      return false;
    }

    // 1. Ensure thumbnail dir exists
    await fs.ensureDir(workingDir);

    // 2. Download Source File
    const file = await bucket.file(filePath);

    await file.download({
      destination: tmpFilePath
    });

    // 3. Resize the images and define an array of upload promises
    const sizes = [64, 128, 256];

    const uploadPromises = sizes.map(async size => {
      const thumbName = `thumb@${size}_${fileName}`;
      const thumbPath = path.join(workingDir, thumbName);

      // Resize source image
      await sharp(tmpFilePath)
        .resize(size, size)
        .toFile(thumbPath);

      // Upload to GCS
      return bucket.upload(thumbPath, {
        destination: path.join(bucketDir, thumbName)
      });
    });

    // 4. Run the upload operations
    await Promise.all(uploadPromises);

    // 5. Cleanup remove the tmp/thumbs from the filesystem
    return fs.remove(workingDir);
  });

Но я получаю следующую ошибку:

Error: Not Found
    at new ApiError (/srv/node_modules/@google-cloud/common/build/src/util.js:58:28)
    at Util.parseHttpRespMessage (/srv/node_modules/@google-cloud/common/build/src/util.js:159:41)
    at Util.handleResp (/srv/node_modules/@google-cloud/common/build/src/util.js:136:74)
    at Duplexify.requestStream.on.on.res (/srv/node_modules/@google-cloud/storage/build/src/file.js:392:31)
    at emitOne (events.js:116:13)
    at Duplexify.emit (events.js:211:7)
    at emitOne (events.js:116:13)
    at DestroyableTransform.emit (events.js:211:7)
    at onResponse (/srv/node_modules/retry-request/index.js:194:19)
    at Request.<anonymous> (/srv/node_modules/retry-request/index.js:149:11)

на bucket.file (...). Download ()

API 2.XX внес некоторые изменения, и я не могу заставить это работать.Кто-нибудь может мне помочь?Спасибо.

1 Ответ

0 голосов
/ 25 октября 2018

Получил работу со следующим кодом:

const functions = require('firebase-functions');
const { Storage } = require('@google-cloud/storage');
const os = require('os');
const path = require('path');
const sharp = require('sharp');
const fs = require('fs-extra');

exports.generateThumbs = functions.storage
  .object()
  .onFinalize(async (object) => {
    const storage = new Storage();
    const bucket = storage.bucket(object.bucket);
    const filePath = object.name;
    const fileName = filePath.split('/').pop();
    const bucketDir = path.dirname(filePath);

    const workingDir = path.join(os.tmpdir(), 'thumbs');
    const tmpFilePath = path.join(workingDir, 'source.png');

    if (fileName.includes('thumb@') || !object.contentType.includes('image')) {
      console.log('exiting function');
      return false;
    }

    // 1. Ensure thumbnail dir exists
    await fs.ensureDir(workingDir);

    // 2. Download Source File
    await  bucket.file(filePath).download({
      destination: tmpFilePath
    });

    // 3. Resize the images and define an array of upload promises
    const sizes = [64, 128, 256];

    const uploadPromises = sizes.map(async size => {
      const thumbName = `thumb@${size}_${fileName}`;
      const thumbPath = path.join(workingDir, thumbName);

      // Resize source image
      await sharp(tmpFilePath)
        .resize(size, size)
        .toFile(thumbPath);

      // Upload to GCS
      return bucket.upload(thumbPath, {
        destination: path.join(bucketDir, thumbName)
      });
    });

    // 4. Run the upload operations
    await Promise.all(uploadPromises);

    // 5. Cleanup remove the tmp/thumbs from the filesystem
    return fs.remove(workingDir);
  });
...