Is it possible to scope Firebase functions to a folder inside a storage bucket?

Viewed 3917

I have tested Firebase functions for storage successfully. However, I havn't seen anywhere a hint how to only invoke the function when a file is added into a folder inside my bucket. The only hint I have seen about scoping the function is for different buckets here.

Is it possible to scope the function to a folder inside my bucket , if yes how? Or would I need to have multiple buckets instead of folders to separate different tasks.

3 Answers

You may check inside the function. Get the "filePath" or "fileDir" on your function and check if it is the folder you want.

const path = require('path');
const filePath = event.data.name;
const fileDir = path.dirname(filePath);

//if you want to check the posts folder only then:

if (fileDir != 'posts') {
    console.log('This is not in post folder');
    return null;
}

Please note that Google Cloud Storage works on a flat filesystem. So practically there are no directories. If you're storing a file like /users/profile_pictures/photo.jpg it is basically all part of the file name. So in reality, there are no directories. There are just files. Which is why there cannot be a trigger on a directory per se. Of course you can work that around by checking the name of the file itself and see whether its start matches a particular string or not.

export const generateThumbnailTrigger = functions.storage.object().onFinalize(async (object) => {
    const filePath = object.name;
    if (filePath?.startsWith('temp/')) {
        console.log('start doing something with the file');
    } else {
        return false;
    }
});
Related