我有一个Cloud Function,可以调整当前上传图像的大小。 调整大小后,我得到了一个新的图像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);
});
答案 0 :(得分:2)
执行写操作的用户在函数中不可用,除非您执行以下任一操作:
在两种情况下,您都希望使用安全规则来验证UID与编写它的用户是否匹配。
答案 1 :(得分:1)
尝试以其他方式解决问题。将文件存储在GCS中,然后将GCS URL存储到Firestone中。在Firestone创建事件上设置触发器,在函数中转换图像并将新链接存储在函数中