-
Notifications
You must be signed in to change notification settings - Fork 584
/
getSignedUrl.ts
59 lines (54 loc) · 2.09 KB
/
getSignedUrl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { HttpRequest } from "@aws-sdk/protocol-http";
import { Client, Command } from "@aws-sdk/smithy-client";
import { BuildMiddleware, MetadataBearer, RequestPresigningArguments } from "@aws-sdk/types";
import { formatUrl } from "@aws-sdk/util-format-url";
import { S3RequestPresigner } from "./presigner";
export const getSignedUrl = async <
InputTypesUnion extends object,
InputType extends InputTypesUnion,
OutputType extends MetadataBearer = MetadataBearer
>(
client: Client<any, InputTypesUnion, MetadataBearer, any>,
command: Command<InputType, OutputType, any, InputTypesUnion, MetadataBearer>,
options: RequestPresigningArguments = {}
): Promise<string> => {
const s3Presigner = new S3RequestPresigner({ ...client.config });
const presignInterceptMiddleware: BuildMiddleware<InputTypesUnion, MetadataBearer> = (next, context) => async (
args
) => {
const { request } = args;
if (!HttpRequest.isInstance(request)) {
throw new Error("Request to be presigned is not an valid HTTP request.");
}
// Retry information headers are not meaningful in presigned URLs
delete request.headers["amz-sdk-invocation-id"];
delete request.headers["amz-sdk-request"];
const presigned = await s3Presigner.presign(request, {
...options,
signingRegion: options.signingRegion ?? context["signing_region"],
signingService: options.signingService ?? context["signing_service"],
});
return {
// Intercept the middleware stack by returning fake response
response: {},
output: {
$metadata: { httpStatusCode: 200 },
presigned,
},
} as any;
};
client.middlewareStack.addRelativeTo(presignInterceptMiddleware, {
name: "presignInterceptMiddleware",
relation: "before",
toMiddleware: "awsAuthMiddleware",
});
let presigned: HttpRequest;
try {
const output = await client.send(command);
//@ts-ignore the output is faked, so it's not actually OutputType
presigned = output.presigned;
} finally {
client.middlewareStack.remove("presignInterceptMiddleware");
}
return formatUrl(presigned);
};