UNPKG

1.84 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash');
4
5const HeaderDate = 'Date';
6
7const RequestID = 'X-Fc-Request-Id';
8
9const CORSMaxAgeSeconds = '3600';
10
11// InvocationError header key for invocation error type header
12const InvocationError = 'x-fc-error-type';
13
14// InvocationLogResult header key for log result of the invocation
15const InvocationLogResult = 'x-fc-log-result';
16
17// MaxMemoryUsage defines the usage of fc invocation
18const MaxMemoryUsage = 'x-fc-max-memory-usage';
19
20// InvocationDuration defines the duration of fc invocation
21const InvocationDuration = 'x-fc-invocation-duration';
22// InvocationCodeChecksum header key for code checksum of the invocation
23
24const InvocationCodeChecksum = 'x-fc-code-checksum';
25// InvocationCodeVersion header key for code version of the invocation
26const InvocationCodeVersion = 'x-fc-invocation-code-version';
27
28const exposedHeaders = [HeaderDate, RequestID, InvocationError, InvocationCodeChecksum, InvocationDuration, MaxMemoryUsage, InvocationLogResult, InvocationCodeVersion];
29
30const CORSExposedHeaders = _.join(exposedHeaders, ',');
31
32function setCORSHeaders(req, res, next) {
33
34 const origin = req.headers.origin;
35 if (origin) {
36 res.header('Access-Control-Allow-Origin', origin);
37 }
38
39 if (req.headers['access-control-request-method']) {
40 res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
41 }
42
43 if (req.headers['access-control-request-headers']) {
44 res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
45 }
46
47 res.header('Access-Control-Expose-Headers', CORSExposedHeaders);
48
49 if (_.toLower(req.method) === 'options') {
50 res.header('Access-Control-Max-Age', CORSMaxAgeSeconds);
51 // intercept OPTIONS method
52 res.sendStatus(200);
53 } else {
54 return next();
55 }
56}
57module.exports = { setCORSHeaders };