繁体   English   中英

如何在Firebase Cloud函数中调用两个函数

[英]How to call two functions in Firebase Cloud functions

我使用一个Cloud Function调整图像大小,然后使用第二个功能将新的图像URL上传到Cloud Firestore。

但是有些东西不起作用,因为第二个功能永远不会运行。 我需要uid和postId,可以在其中更新网址。

如何在Firestore中调用第二个函数来更新img url?

const { functions, 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);

      //second function

        functions.firestore.document('users/{uid}/posts/{id}').onCreate(async (snap, context) => {
            console.log(context.params);
            const uid = context.params.uid;

            const userPost = functions.firestore.doc('users/{uid}/posts}');
            userPost.update({
                url: newUrl,
            });
        });

        return fse.remove(workingDir);
    });

您的第二个功能似乎嵌入在第一个功能中。 这行不通。 所有功能定义都必须在顶层,以便Firebase CLI可以检测到它们并分别进行部署。

如果您实际上不需要两个单独的函数定义,则只需在一个函数中执行所有工作即可,不要尝试使用函数SDK来完成任何工作。 Functions SDK仅用于定义要部署的功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM