1
- import fastifyPlugin from "fastify-plugin" ;
2
-
3
1
import {
4
2
GetObjectCommand ,
5
3
S3Client ,
6
4
} from "@aws-sdk/client-s3" ;
7
5
import { getSignedUrl } from "@aws-sdk/s3-request-presigner" ;
6
+ import fastifyPlugin from "fastify-plugin" ;
7
+
8
+ import { Nullable } from "./typings/common.js" ;
8
9
9
10
10
11
/**
@@ -16,12 +17,12 @@ const PRE_SIGNED_URL_EXPIRY_TIME_SECONDS = 3600;
16
17
* Class to manage Simple Storage Service (S3) objects.
17
18
*/
18
19
class S3Manager {
19
- #s3Client;
20
+ readonly #s3Client;
20
21
21
22
/**
22
- * @param { string } region
23
+ * @param region
23
24
*/
24
- constructor ( region ) {
25
+ constructor ( region : string ) {
25
26
this . #s3Client = new S3Client ( {
26
27
region : region ,
27
28
} ) ;
@@ -30,11 +31,11 @@ class S3Manager {
30
31
/**
31
32
* Generates a pre-signed URL for accessing an S3 object.
32
33
*
33
- * @param { string } s3UriString The S3 object URI string.
34
- * @return { Promise<string> } The pre-signed URL string.
34
+ * @param s3UriString The S3 object URI string.
35
+ * @return The pre-signed URL string.
35
36
* @throws {Error } If a pre-signed URL couldn't be generated.
36
37
*/
37
- async getPreSignedUrl ( s3UriString ) {
38
+ async getPreSignedUrl ( s3UriString : string ) {
38
39
const s3Uri = new URL ( s3UriString ) ;
39
40
const command = new GetObjectCommand ( {
40
41
Bucket : s3Uri . hostname ,
@@ -49,7 +50,10 @@ class S3Manager {
49
50
expiresIn : PRE_SIGNED_URL_EXPIRY_TIME_SECONDS ,
50
51
}
51
52
) ;
52
- } catch ( error ) {
53
+ } catch ( error : unknown ) {
54
+ if ( false === error instanceof Error ) {
55
+ throw error ;
56
+ }
53
57
throw new Error ( `Failed to generate pre-signed URL: ${ error . message } ` ) ;
54
58
}
55
59
}
@@ -59,12 +63,18 @@ class S3Manager {
59
63
* Initializes a Fastify plugin, which decorates the application with an S3 manager at the
60
64
* "s3Manager" property when all plugin options are valid.
61
65
*/
62
- export default fastifyPlugin ( async ( app , options ) => {
66
+ export default fastifyPlugin ( async ( app , options : { region : Nullable < string > } ) => {
63
67
const { region} = options ;
64
68
if ( null === region ) {
65
69
return ;
66
70
}
67
71
68
72
console . log ( `Initializing S3Manager with region="${ region } "...` ) ;
69
- await app . decorate ( "s3Manager" , new S3Manager ( region ) ) ;
73
+ app . decorate ( "s3Manager" , new S3Manager ( region ) ) ;
70
74
} ) ;
75
+
76
+ declare module "fastify" {
77
+ interface FastifyInstance {
78
+ s3Manager ?: S3Manager ;
79
+ }
80
+ }
0 commit comments