javascript - 如何在 Firebase Cloud 函数中调用两个函数
问题描述
我使用一个 Cloud Function 来调整图像大小,第二个用于将新图像 URL 上传到 Cloud Firestore。
但是有些东西不起作用,因为第二个函数永远不会运行。我需要可以更新 url 的 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 仅用于定义要部署的功能。
推荐阅读
- java - 使用 Java 设置操作计算器 - 计算器部分不起作用
- android - 添加外部库时出现 Android Studio 错误
- caffe - 为什么pycaffe向后的结果总是0?
- java - 如何在android studio中删除部分安装的sdk
- javascript - 如果您确实需要优化回流
- c++ - arma::Cube 的 row() 或 col() 成员似乎不起作用
- c# - 如何匹配新的 StackTrace 以抛出 Exception.StackTrace
- firebase - Flutter Firebase/Firestore 文档对 Future Builder 列表视图的参考
- php - 特定类别的木材/ TWIG spearate 模板
- angular - 如何在 Angular 6 中替换父组件上的子组件?