|
| 1 | +// https://itty.dev/itty-router/routers/autorouter |
| 2 | +import { AutoRouter } from 'itty-router'; |
1 | 3 | import { |
2 | | - CreateBucketCommand, |
3 | | - PutObjectCommand, |
4 | | - S3Client, |
| 4 | + CreateBucketCommand, |
| 5 | + PutObjectCommand, |
| 6 | + S3Client, |
5 | 7 | } from '@aws-sdk/client-s3'; |
6 | | -import { ResponseBuilder } from '@fermyon/spin-sdk'; |
7 | 8 | import { v4 as uuid } from 'uuid'; |
8 | 9 |
|
9 | 10 | const s3 = new S3Client({ |
10 | | - endpoint: '<Backblaze b2 endpoint>', |
11 | | - region: '<>', |
12 | | - credentials: { |
13 | | - accessKeyId: '<>', |
14 | | - secretAccessKey: '<>', |
15 | | - }, |
| 11 | + endpoint: '<Backblaze b2 endpoint>', |
| 12 | + region: '<>', |
| 13 | + credentials: { |
| 14 | + accessKeyId: '<>', |
| 15 | + secretAccessKey: '<>', |
| 16 | + }, |
16 | 17 | }); |
| 18 | +let router = AutoRouter(); |
17 | 19 |
|
18 | | -export async function handler(_req: Request, res: ResponseBuilder) { |
19 | | - try { |
20 | | - let bucketName = 'spin-sdk-bucket-' + uuid(); |
21 | | - let keyName = 'hello_world.txt'; |
22 | | - await s3.send(new CreateBucketCommand({ Bucket: bucketName })); |
| 20 | +// Route ordering matters, the first route that matches will be used |
| 21 | +// Any route that does not return will be treated as a middleware |
| 22 | +// Any unmatched route will return a 404 |
| 23 | +router |
| 24 | + .get("/", async () => { |
| 25 | + try { |
| 26 | + let bucketName = 'spin-sdk-bucket-' + uuid(); |
| 27 | + let keyName = 'hello_world.txt'; |
| 28 | + await s3.send(new CreateBucketCommand({ Bucket: bucketName })); |
23 | 29 |
|
24 | | - await s3.send( |
25 | | - new PutObjectCommand({ |
26 | | - Bucket: bucketName, |
27 | | - Key: keyName, |
28 | | - Body: 'Hello World!', |
29 | | - }), |
30 | | - ); |
31 | | - res.send(`Successfully uploaded data to ${bucketName}/${keyName}`); |
32 | | - } catch (e: any) { |
33 | | - res.status(500); |
34 | | - res.send(`error: ${e}`); |
35 | | - } |
36 | | -} |
| 30 | + await s3.send( |
| 31 | + new PutObjectCommand({ |
| 32 | + Bucket: bucketName, |
| 33 | + Key: keyName, |
| 34 | + Body: 'Hello World!', |
| 35 | + }), |
| 36 | + ); |
| 37 | + return new Response(`Successfully uploaded data to ${bucketName}/${keyName}`); |
| 38 | + } catch (e: any) { |
| 39 | + return new Response(`error: ${e}`, { status: 500 }); |
| 40 | + } |
| 41 | + }) |
| 42 | + |
| 43 | +//@ts-ignore |
| 44 | +addEventListener('fetch', async (event: FetchEvent) => { |
| 45 | + event.respondWith(router.fetch(event.request)); |
| 46 | +}); |
0 commit comments