Firebase 功能 - 在上传到存储时调整大小并覆盖现有图像

Firebase Function - Resize and overwrite existing image on upload to Storage

所以我按照 Google's official sample 创建了一个云存储触发的 Firebase 函数,该函数将从上传的图像创建调整大小的缩略图并将它们上传到存储。这里简化一下:

exports.generateThumbnail = functions.storage.object().onChange(event => {

    // get the uploaded file data (bucket, name, type...)

    // return if the file is not an image or name begins with "thumb_"

    // download the uploaded image in a temporary local file,
    // resize it using ImageMagick
    // upload it to storage with the name "thumb_<filename>"

}

但是,当新的缩略图上传时,该函数会再次触发,如此循环。如果上传的文件有 "thumb_" 前缀,他们通过返回来避免这种情况。

然后你得到两张图片(原始图片和缩略图),我想用缩略图重写现有图片所以我只有一张图片有原始路径.

我不知道该怎么做,因为我不知道如何在不更改名称的情况下避开重新上传循环。我可以在上传缩略图后删除原图,但是指向原图的 link 已经返回并保存在实时数据库中(这些图像是用户的个人资料图片)。

在查看 @google-cloud/storage npm 模块中的 bucket.js 文档后,我终于设法用缩略图覆盖了原始 file/path 并且也避免了循环,

可以通过在上传缩略图时附加自定义元数据,并在下次触发该功能时测试该元数据来完成。

我将只post我所做的更改,其余与链接示例中的相同。

这是测试:

const filePath = event.data.name
const metadata = event.data.metadata

if (metadata.isThumb) {
    console.log('Exiting: Already a thumbnail')
    return
}

这是 spawn 承诺 returns 的部分:

    return spawn(/* ... */)
}).then(_ => {
    console.log('Thumbnail created locally.')
    metadata.isThumb = true  // We add custom metadata
    const options = {
        destination: filePath,  // Destination is the same as original
        metadata: { metadata: metadata }
    }
    // We overwrite the (bigger) original image but keep the path
    return bucket.upload(/* localThumb */, options)
})