【发布时间】: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