-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
66 lines (56 loc) · 1.92 KB
/
index.js
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
const R = require('ramda');
const getAllowedOrigin = (origin, allowedOrigins) => {
if (R.includes('*', allowedOrigins)) {
return origin;
}
return R.find((allowedOrigin) => allowedOrigin === origin, allowedOrigins);
};
const getCorsHeaders = (
event,
{ allowedOrigins, exposeHeaders, maxAge, credentials, allowMethods, allowHeaders } = {}
) => {
const headers = {};
if (allowedOrigins) {
const origin = getAllowedOrigin(R.path(['headers', 'origin'], event), allowedOrigins);
if (origin) {
headers['access-control-allow-origin'] = origin;
}
}
if (credentials && !R.includes('*', allowedOrigins)) {
headers['access-control-allow-credentials'] = credentials;
}
if (!R.isNil(exposeHeaders) && !R.isEmpty(exposeHeaders)) {
headers['access-control-expose-headers'] = exposeHeaders.join(', ');
}
if (maxAge !== undefined) {
headers['access-control-max-age'] = maxAge;
}
if (!R.isNil(allowMethods) && !R.isEmpty(allowMethods)) {
headers['access-control-allow-methods'] = allowMethods.join(', ');
}
if (!R.isNil(allowHeaders) && !R.isEmpty(allowHeaders)) {
headers['access-control-allow-headers'] = allowHeaders.join(', ');
}
return headers;
};
const corsMiddleware = (opts) => ({
after: async (handler) => {
// eslint-disable-next-line no-param-reassign
handler.response.headers = {
...handler.response.headers,
...getCorsHeaders(handler.event, opts),
};
},
onError: async (handler) => {
// eslint-disable-next-line no-param-reassign
handler.response = R.assocPath(
['headers'],
{
...R.pathOr({}, ['response', 'headers'], handler),
...getCorsHeaders(handler.event, opts),
},
handler.response
);
},
});
module.exports = corsMiddleware;