Created
April 24, 2021 14:04
-
-
Save devdilson/ef69a38c2e8fa4813d0942c8aeab1de1 to your computer and use it in GitHub Desktop.
Generate a S3 pre-signed url using cloudflare worker.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as AWS from 'aws-sdk'; | |
| # Your S3 compatible API secrets | |
| declare var AWS_ACCESS_KEY: string; | |
| declare var AWS_SECRET_ACCESS_KEY: string; | |
| # Your endpoint and bucket name. | |
| const S3_ENDPOINT = 'example.myapp.xyz'; | |
| const S3_BUCKET = 'mybucket'; | |
| const s3 = new AWS.S3({ | |
| credentials: new AWS.Credentials(AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY), | |
| endpoint: new AWS.Endpoint(S3_ENDPOINT), | |
| signatureVersion: 'v4', | |
| s3ForcePathStyle: true | |
| }); | |
| const TTL_SECONDS = 5 * 60; | |
| addEventListener('fetch', (event) => { | |
| event.respondWith(handleRequest(event)) | |
| }) | |
| class ApiResponse extends Response { | |
| constructor(body?: BodyInit | null, init?: ResponseInit) { | |
| super(body, init) | |
| this.headers.set("Access-Control-Allow-Origin", "*"); | |
| } | |
| } | |
| export async function handleRequest(event: FetchEvent): Promise<Response> { | |
| let response; | |
| let file = event.request.url.split('/download/token/')[1]; | |
| if (!file) { | |
| response = { | |
| status: 400, | |
| error: 'Bad url, missing resource' | |
| }; | |
| } else { | |
| const url = s3.getSignedUrl('getObject', { | |
| Bucket: S3_BUCKET, | |
| Key: file, | |
| Expires: TTL_SECONDS | |
| }); | |
| response = { | |
| url: url, | |
| resource: file | |
| }; | |
| } | |
| const ret = new ApiResponse(JSON.stringify(response, null, 4), { | |
| status: response.status | |
| }); | |
| return ret; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment