Reputation: 135
I have a Cloud Function which resizes the current uploaded image. After the resizing happened and I get a new image URL. And this new url I would like to add/update to the users post-data who uploaded the image to Firestore.
But my problem is that I don't know how to get the current user uid and the created postId after upload to firestore
Code:
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);
});
Upvotes: 0
Views: 324
Reputation: 75715
Try to catch the problem on other way. Store the file in GCS, and then store the GCS url into Firestone. Set a trigger on Firestone create event, transform the image in the function and store the new link in the function
Upvotes: 1
Reputation: 317352
The user who made the write is not available in the function unless you do either:
In both cases, you will want to use security rules to validate the UID matches the user who wrote it.
Upvotes: 2