-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequestHelpers.js
50 lines (48 loc) · 1.61 KB
/
requestHelpers.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
// standard helper for post body processing
export function stdPostBody(req) {
try {
return JSON.parse(req.body);
}
catch(e) {
// empty body response
return null
}
}
// failed request for standardized response
export function invalidRequest(res, reason, status = 400) {
return res.status(status).json({
status: status,
reason: reason
});
}
// standard response w/ headers
export function stdResponse(res, data = {}, respOptions = {}) {
const headers = {
status: 200,
methods: "OPTIONS, POST",
origin: "*",
headers: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
credentials: "true",
...respOptions
};
res.setHeader("Access-Control-Allow-Methods", headers.methods);
res.setHeader("Access-Control-Allow-Origin", headers.origin);
res.setHeader("Access-Control-Allow-Credentials", headers.credentials);
res.setHeader("Access-Control-Allow-Headers", headers.headers);
// cache is opt in but also support buster flag to ensure we force NOT hitting a cache
if (headers.cache && headers.cache !== 'bust') {
res.setHeader('Cache-Control', `max-age=0, s-maxage=${headers.cache}, stale-while-revalidate=${headers.cache}`);
}
// support non-json based responses. If type is set for content type
// then we just send the status / data in the format provided
if (headers.type) {
res.setHeader('Content-Type', headers.type);
return res.status(headers.status).send(data);
}
else {
return res.status(headers.status).json({
status: headers.status,
data: data
});
}
}