Изменение размера изображения с помощью облачной функции Firebase - PullRequest
0 голосов
/ 05 июля 2019

Я следил за следующим видео и сообщением в блоге о функциях Firebase по изменению размера изображения, кажется, что многое изменилось с момента выхода видео и пост-релиза.Я смог найти решения некоторых ошибок, но не всех:

Ниже приведена моя версия кода:

import * as functions from 'firebase-functions';

import { Storage } from '@google-cloud/storage';
const gcs = new Storage();

import { tmpdir } from 'os';
import { join, dirname } from 'path';

const sharp = require('sharp');
const fs = require('fs-extra');

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

    const workingDir = join(tmpdir(), 'thumbs');
    const tmpFilePath = 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 = join(workingDir, thumbName);

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

      // Upload to GCS
      return bucket.upload(thumbPath, {
        destination: 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);
  });

С этим кодом я получаю следующие ошибки:


src / index.ts: 17: 22 - ошибка TS2532: Возможно, объект не определен.

17 const fileName = filePath.split ('/'). Pop ();~~~~~~~~

src / index.ts: 18: 31 - ошибка TS2345: Аргумент типа 'строка |undefined 'не может быть назначен параметру типа' string '.Тип 'undefined' нельзя назначить типу 'string'.

18 const bucketDir = dirname (filePath);~~~~~~~~

src / index.ts: 23: 9 - ошибка TS2532: Возможно, объект не определен.

23 if (fileName.includes ('thumb @)') ||! object.contentType.includes (' image ')) {~~~~~~~~

src / index.ts: 23: 41 - ошибка TS2532: Возможно, объект не определен.

23 if (fileName.include ('thumb @') ||! Object.contentType.includes ('image')) {~~~~~~~~~~~~~~~~~~~

src / index.ts: 32: 23 - ошибка TS2345: Аргумент типа 'строка |undefined 'не может быть назначен параметру типа' string '.Тип 'undefined' нельзя назначить типу 'string'.

32 await bucket.file (filePath) .download ({

) Буду очень благодарен, если кто-нибудь сможет мне помочьна этом.

...