使用Firebase Cloud功能调整图像大小

时间:2019-07-05 16:03:36

标签: javascript angular typescript firebase google-cloud-functions

我遵循以下videoblog post关于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:“字符串|类型”的参数未定义”不能分配给“字符串”类型的参数。     无法将“未定义”类型分配给“字符串”类型。

     

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.includes('thumb @')||!object.contentType.includes('image')){                                              ~~~~~~~~~~~~~~~~~

     

src / index.ts:32:23-错误TS2345:“字符串|类型”的参数未定义”不能分配给“字符串”类型的参数。     无法将“未定义”类型分配给“字符串”类型。

     

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

如果有人可以帮助我,我将非常感谢。

0 个答案:

没有答案