UNPKG

cloud-presign

Version:

A unified presigned URL generator for multiple cloud platforms

80 lines (79 loc) 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GcpProvider = void 0; const storage_1 = require("@google-cloud/storage"); const types_1 = require("../types"); const common_1 = require("./common"); class GcpProvider { constructor(config, defaultExpiration) { this.common = new common_1.Common(); this.bucket = config.bucket; this.defaultExpiration = defaultExpiration; const storageOptions = { projectId: config.projectId, }; // Use key file if provided if (config.keyFilename) { storageOptions.keyFilename = config.keyFilename; } this.storage = new storage_1.Storage(storageOptions); } async generatePresignedUrl(params, options) { const expiration = (options === null || options === void 0 ? void 0 : options.expiration) || this.defaultExpiration; const method = params.method || types_1.HttpMethod.GET; let fileName = params.key; let key = params.key; // Convert HTTP method to GCP action let action; switch (method) { case types_1.HttpMethod.GET: action = 'read'; break; case types_1.HttpMethod.PUT: case types_1.HttpMethod.POST: fileName = await this.common.generateFileUniqueName(params.key); key = params.prefix ? `${params.prefix}/${fileName}` : fileName; action = 'write'; break; case types_1.HttpMethod.DELETE: action = 'delete'; break; default: throw new Error(`Unsupported HTTP method: ${method}`); } // Get the bucket const bucket = this.storage.bucket(this.bucket); const file = bucket.file(key); // Generate signed URL const [presignedUrl] = await file.getSignedUrl({ version: 'v4', action, expires: Date.now() + expiration * 1000, contentType: params.contentType, extensionHeaders: params.metadata, }); // Calculate expiration date const expiresAt = new Date(Date.now() + expiration * 1000).toISOString(); const url = presignedUrl.split('?')[0]; // Build response const response = { key, presignedUrl, url: params.isPublic ? url : "", method, expiresAt, headers: {}, }; // Add content type header for upload requests if ((method === types_1.HttpMethod.PUT || method === types_1.HttpMethod.POST) && params.contentType) { response.headers['Content-Type'] = params.contentType; } return response; } async makeFilePublic(key) { const bucket = this.storage.bucket(this.bucket); const file = bucket.file(key); await file.makePublic(); } } exports.GcpProvider = GcpProvider;