Angular Generating Thumbnail error with firebase

Viewed 24

I've been having some issues regarding the one cloud function using this image thumbnail resizer https://fireship.io/lessons/image-thumbnail-resizer-cloud-function/. The function works but if 2 people would upload at the same time it would use only one of the images. This is the current function below.

export const generateThumbnail = functions.region(location)
  .pubsub.topic('new-trade')
  .onPublish((msg, context) => {
    const messageBody = JSON.parse(Buffer.from(msg.data, 'base64').toString()) as NewTradeData;

    return new Promise<void>(async (resolve, reject) => {
      // Fetch the trade object from firestore
      const trade = await admin.firestore().collection('trades').doc(messageBody.tradeId).get();
      const tradeData = trade.data();

      if (!tradeData) {
        reject('No Trade data');
        return;
      }

      const workingDir = join(tmpdir(), 'thumbs');
      const tmpFilePath = join(workingDir ,'source.png');

      await fs.ensureDir(workingDir);

      // Fetch the first file in the `photos` array from storage
      await admin.storage().bucket().file(tradeData.items[0].photos[0]).download({destination: tmpFilePath});

      const thumbPath = join(workingDir ,'thumbnail.png');

      // Resize the image
      await sharp(tmpFilePath).resize(400,256).toFile(thumbPath);

      // Push the thumbnail back to storage
      const thumbStoragePath = `images/${messageBody.tradeId}/thumbnail.png`;
      await admin.storage().bucket().upload(thumbPath, {destination: thumbStoragePath});
      // Update the trade object with a path to the thumbnail
      await admin.firestore().collection('trades').doc(messageBody.tradeId).update({thumbnail: thumbStoragePath});

      // Clean up
      await fs.remove(workingDir);
      resolve();
    });
  });

We then tried to change the tmpFilePath and thumbPath to have a unique id for storage for race conditions.

const tmpFilePath = join(workingDir, messageBody.tradeId ,'/source.png');
const thumbPath = join(workingDir, messageBody.tradeId ,'/thumbnail.png');

I get this error on firebase Error: ENOENT: no such file or directory, open '/tmp/thumbs/Z6QiR9JlNYvHHk57IAwx/source.png' But it seems to have broken the function. Is there any pointers you could give to resolve this?

0 Answers
Related