lukas34tfd
lukas34tfd

Reputation: 135

Update firestore in cloud functions

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

Answers (2)

guillaume blaquiere
guillaume blaquiere

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

Doug Stevenson
Doug Stevenson

Reputation: 317352

The user who made the write is not available in the function unless you do either:

  1. Use the UID as part of the path to the file, and parse that UID out of the path in the function.
  2. Write the UID as part of the metadata for the file upload, then read that in the function.

In both cases, you will want to use security rules to validate the UID matches the user who wrote it.

Upvotes: 2

Related Questions