/
region-redirect-endpoint-middleware.ts
50 lines (47 loc) · 1.48 KB
/
region-redirect-endpoint-middleware.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
import {
HandlerExecutionContext,
MetadataBearer,
RelativeMiddlewareOptions,
SerializeHandler,
SerializeHandlerArguments,
SerializeHandlerOutput,
SerializeMiddleware,
} from "@smithy/types";
import { PreviouslyResolved } from "./region-redirect-middleware";
/**
* @internal
*/
export const regionRedirectEndpointMiddleware = (config: PreviouslyResolved): SerializeMiddleware<any, any> => {
return <Output extends MetadataBearer>(
next: SerializeHandler<any, Output>,
context: HandlerExecutionContext
): SerializeHandler<any, Output> =>
async (args: SerializeHandlerArguments<any>): Promise<SerializeHandlerOutput<Output>> => {
const originalRegion = await config.region();
const regionProviderRef = config.region;
if (context.__s3RegionRedirect) {
config.region = async () => {
config.region = regionProviderRef;
return context.__s3RegionRedirect;
};
}
const result = await next(args);
if (context.__s3RegionRedirect) {
const region = await config.region();
if (originalRegion !== region) {
throw new Error("Region was not restored following S3 region redirect.");
}
}
return result;
};
};
/**
* @internal
*/
export const regionRedirectEndpointMiddlewareOptions: RelativeMiddlewareOptions = {
tags: ["REGION_REDIRECT", "S3"],
name: "regionRedirectEndpointMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware",
};