【问题标题】:Update firestore in cloud functions更新云功能中的 Firestore
【发布时间】:2019-12-13 17:27:59
【问题描述】:

我有一个调整当前上传图像大小的云函数。 调整大小后,我得到了一个新的图像 URL。我想将这个新网址添加/更新到将图像上传到 Firestore 的用户发布数据。

但我的问题是上传到firestore后不知道如何获取当前用户uid和创建的postId

代码:

const { functions, firestore, tmpdir, dirname, join, sharp, fse, gcs } = require('../../admin');

const runtimeOpts = {
    timeoutSeconds: 120,
    memory: '1GB',
};

exports.resizeImages = functions
    .runWith(runtimeOpts)
    .storage.object()
    .onFinalize(async (object, context) => {
        const bucket = gcs.bucket(object.bucket);
        const filePath = object.name;
        const fileName = filePath.split('/').pop();
        const bucketDir = dirname(filePath);

        const workingDir = join(tmpdir(), 'resize');
        const tmpFilePath = join(workingDir, 'source.png');

        if (fileName.includes('@s_') || !object.contentType.includes('image')) {
            return false;
        }

        await fse.ensureDir(workingDir);
        await bucket.file(filePath).download({ destination: tmpFilePath });

        // creates 3 new images with these sizes..
        const sizes = [1920, 720, 100];
        var newUrl = null;

        const uploadPromises = sizes.map(async size => {
            const ext = fileName.split('.').pop();
            const imgName = fileName.replace(`.${ext}`, '');
            const newImgName = `${imgName}@s_${size}.${ext}`;
            var imgPath = join(workingDir, newImgName);
            newUrl = imgPath;
            await sharp(tmpFilePath)
                .resize({ width: size })
                .toFile(imgPath);

            return bucket.upload(imgPath, {
                destination: join(bucketDir, newImgName),
            });
        });

        await Promise.all(uploadPromises);

        // update post on firstore with `newUrl`

        const postId = null;
        const userId = null;

        const postDb = firestore.doc(`posts/${postId}`);
        const userDb = firestore.doc(`users/${userId}`);

        postDb.update({
            url: newUrl,
        });

        userDb.update({
            url: newUrl,
        });

        return fse.remove(workingDir);
    });

【问题讨论】:

    标签: javascript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    除非您这样做,否则进行写入的用户在函数中不可用:

    1. 使用 UID 作为文件路径的一部分,并从函数的路径中解析 UID。
    2. 将 UID 作为文件上传元数据的一部分写入,然后在函数中读取。

    在这两种情况下,您都需要使用安全规则来验证 UID 是否与编写它的用户匹配。

    【讨论】:

    • 我如何将 UID 作为路径的一部分写入?
    • 把uid放在你正在写的对象的路径中。例如:/users/UID/object.png
    【解决方案2】:

    尝试以其他方式解决问题。将文件存储在 GCS 中,然后将 GCS url 存储到 Firestone。在Firestone创建事件上设置触发器,在函数中转换图像并将新链接存储在函数中

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2019-08-07
      • 1970-01-01
      • 2021-03-27
      • 2018-05-09
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多