-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddlewares.js
44 lines (40 loc) · 1.47 KB
/
middlewares.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
/** @module middlewares */
const R = require("ramda");
const { jsonOr } = require("./conversions");
const { vsprintf } = require("sprintf-js");
const _ = require("lodash");
/** Appends data to the request or appends the passed default value
* @method
*/
const withDataOr = R.curry((key, defaultValue, req, res, next) => {
req[key] = jsonOr(req.get(key), defaultValue);
next();
});
/** Blocks with an error any request that does not have the passed content type
* @method
*/
const hasContentTypes = (
contentTypes,
{ status = 415, msg = { type: "error", msg: `Unsuported context-type` } } = {}
) => ({ headers }, res, next) =>
(!contentTypes.includes(headers["content-type"]) && res.status(status).send(msg)) || next();
/** Add language and translation capabilities to the request
* @method
*/
const withTranslate = R.curry(({ translations, defaultLang, localeHeaderKey, localeQueryKey }, req, res, next) => {
const localeSplit = (
(req.query && _.get(req.query, localeQueryKey, null)) ||
(req.headers && req.headers[localeHeaderKey]) ||
""
)
.toLowerCase()
.split(/[-_]/g);
req.lang = (localeSplit && localeSplit[0]) || defaultLang;
const { lang } = req;
req.translate = (text, args = []) => {
const translation = translations[text] && translations[text][lang] ? translations[text][lang] : text;
return args.length ? vsprintf(translation, args) : translation;
};
next();
});
module.exports = { withDataOr, withTranslate, hasContentTypes };