fitlien-services/functions/src/storage/accessFile.ts

46 lines
1.5 KiB
TypeScript

import { onRequest } from "firebase-functions/v2/https";
import { Request } from "firebase-functions/v2/https";
import * as path from 'path';
import { getCorsHandler } from "../shared/middleware";
import { getLogger, getAdmin } from "../shared/config";
const corsHandler = getCorsHandler();
const admin = getAdmin();
const logger = getLogger();
export const accessFile = onRequest({
region: '#{SERVICES_RGN}#'
}, async (request: Request, response) => {
return corsHandler(request, response, async () => {
try {
const filePath = request.query.path as string;
if (!filePath) {
response.status(400).send('File path is required');
return;
}
const expirationMs = 60 * 60 * 1000;
const bucket = admin.storage().bucket();
const file = bucket.file(filePath);
const [exists] = await file.exists();
if (!exists) {
response.status(404).send('File not found');
return;
}
const [signedUrl] = await file.getSignedUrl({
action: 'read',
expires: Date.now() + expirationMs,
responseDisposition: `attachment; filename="${path.basename(filePath)}"`,
});
response.redirect(signedUrl);
logger.info(`File access redirect for ${filePath}`);
} catch (error) {
logger.error('Error accessing file:', error);
response.status(500).send('Error accessing file');
}
});
});