UNPKG

cloud-presign

Version:

A unified presigned URL generator for multiple cloud platforms

90 lines (89 loc) 3.45 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AwsProvider = void 0; const client_s3_1 = require("@aws-sdk/client-s3"); const s3_request_presigner_1 = require("@aws-sdk/s3-request-presigner"); const types_1 = require("../types"); const common_1 = require("./common"); class AwsProvider { constructor(config, defaultExpiration) { this.common = new common_1.Common(); this.config = config; this.defaultExpiration = defaultExpiration; const clientConfig = { region: config.region, credentials: { accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey, }, }; // Add endpoint for compatible services like MinIO, Digital Ocean, etc. if (config.endpoint) { clientConfig.endpoint = config.endpoint; clientConfig.forcePathStyle = true; } this.client = new client_s3_1.S3Client(clientConfig); } 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; const fileName = await this.common.generateFileUniqueName(params.key); const key = `${params.prefix}/${fileName}`; // Define command based on HTTP method let command; switch (method) { case types_1.HttpMethod.GET: command = new client_s3_1.GetObjectCommand({ Bucket: this.config.bucket, Key: params.key, }); break; case types_1.HttpMethod.PUT: command = new client_s3_1.PutObjectCommand({ Bucket: this.config.bucket, Key: key, ContentType: params.contentType, Metadata: params.metadata, }); break; case types_1.HttpMethod.DELETE: command = new client_s3_1.DeleteObjectCommand({ Bucket: this.config.bucket, Key: params.key, }); break; default: throw new Error(`Unsupported HTTP method: ${method}`); } // Generate the signed URL const presignedUrl = await (0, s3_request_presigner_1.getSignedUrl)(this.client, command, { expiresIn: expiration, }); const url = presignedUrl.split('?')[0]; // Calculate expiration date const expiresAt = new Date(Date.now() + expiration * 1000).toISOString(); // Build response const response = { key, presignedUrl, url: params.isPublic ? url : '', method, expiresAt, headers: {}, }; // Add content type header for PUT requests if (method === types_1.HttpMethod.PUT && params.contentType) { response.headers['Content-Type'] = params.contentType; } return response; } async makeFilePublic(key) { const command = new client_s3_1.PutObjectAclCommand({ Bucket: this.config.bucket, Key: key, ACL: "public-read", }); await this.client.send(command); } } exports.AwsProvider = AwsProvider;