Back

Access the storage from a function

  • 0
  • Self Hosted
  • Functions
  • Storage
kauly
2 May, 2024, 04:51

Hello guys,

It's my first function and I'm trying to download a file from my storage and return it but it's not working. The error message is "failed to fetch". The same error occurs when accessing the database so seems that the function is not able to talk with the other appwrite services.

TypeScript
export default async ({ res, req, log, error }: Context) => {
    if (!APPWRITE_PROJECT_ID || !APPWRITE_BUCKET_ID || !APPWRITE_API_ENDPOINT || !APPWRITE_API_KEY) {
        error(
            "Please make sure you have environment variables set.",
        );
        return;
    }
    const client = new Client()
        .setEndpoint(APPWRITE_API_ENDPOINT) // Your API Endpoint
        .setProject(APPWRITE_PROJECT_ID)
        .setKey(APPWRITE_API_KEY);

  const bucket = new Storage(client);

  const fileId =  req.path.replace(/^(\/)|(\/)$/g, '');
    log("FILE ID: " + fileId);
    log("BUCKET ID: " + APPWRITE_BUCKET_ID);
    if(req.method === 'GET') {
        try {
            const file = await bucket.getFileDownload(APPWRITE_BUCKET_ID,  fileId);
            return res.send(file, 200);
        } catch (err) {
            error(err.message)
            return res.json({ error: err.message }, 500);
        }
        
    }
};
TL;DR
Developers are encountering a "failed to fetch" error when trying to download a file from storage within a function due to inability to communicate with other appwrite services. The issue may stem from missing environment variables.
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more