-
Notifications
You must be signed in to change notification settings - Fork 5
/
attainCors.ts
81 lines (71 loc) · 2.29 KB
/
attainCors.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { CorsOptions, CorsOptionsDelegate } from "./types.ts";
import { Cors } from "./cors.ts";
interface Req {
method: string;
headers: {
get(headerKey: string): string | null | undefined;
};
}
interface Res {
status: (status: number) => any;
headers: {
get(headerKey: string): string | null | undefined;
set(headerKey: string, headerValue: string): any;
};
send: (body: any) => any;
end(...args: any): any;
}
/**
* attainCors middleware wrapper
* @param o CorsOptions | CorsOptionsDelegate
* @link https://github.com/tajpouria/cors/blob/master/README.md#cors
*/
export const attainCors = <
RequestT extends Req = any,
ResponseT extends Res = any,
MiddlewareT extends (request: RequestT, response: ResponseT) => any = any,
>(
o?: CorsOptions | CorsOptionsDelegate<RequestT>,
): MiddlewareT => {
const corsOptionsDelegate = Cors.produceCorsOptionsDelegate<
CorsOptionsDelegate<RequestT>
>(o);
return async function cors(request, response) {
try {
const fakeNext = () => undefined;
const options = await corsOptionsDelegate(request);
const corsOptions = Cors.produceCorsOptions(options || {});
const originDelegate = Cors.produceOriginDelegate(corsOptions);
if (originDelegate) {
const requestMethod = request.method;
const getRequestHeader = (headerKey: string) =>
request.headers.get(headerKey);
const getResponseHeader = (headerKey: string) =>
response.headers.get(headerKey);
const setResponseHeader = (headerKey: string, headerValue: string) =>
response.headers.set(headerKey, headerValue);
const setStatus = (statusCode: number) => response.status(statusCode);
const end = response.end();
const origin = await originDelegate(getRequestHeader("origin"));
if (origin) {
corsOptions.origin = origin;
new Cors({
corsOptions,
requestMethod,
getRequestHeader,
getResponseHeader,
setResponseHeader,
setStatus,
next: fakeNext,
end,
}).configureHeaders();
}
}
if (request.method === "OPTIONS") {
response.send("");
}
} catch (error) {
console.error(error);
}
} as MiddlewareT;
};