UNPKG

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