/
utils.js
49 lines (36 loc) · 1.39 KB
/
utils.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
'use strict';
const cuid = require('cuid');
const { createHash } = require('crypto');
module.exports = {
toPlainOrEmptyObject: obj => typeof obj === 'object' && !Array.isArray(obj) ? obj : {},
nullIfEmpty: o => o && (Object.keys(o).length > 0 ? o : null),
isPlainObject: obj => typeof obj === 'object' && !Array.isArray(obj),
normalizeQuery: query =>
// foreach key, get the last element if it's an array
Object.keys(query).reduce((q, param) => {
q[param] = [].concat(query[param]).pop();
return q;
}, {}),
normalizeMultiValueQuery: query =>
// foreach key, ensure that the value is an array
Object.keys(query).reduce((q, param) => {
q[param] = [].concat(query[param]);
return q;
}, {}),
capitalizeKeys: o => {
const capitalized = {};
for (let key in o) { // eslint-disable-line prefer-const
capitalized[key.replace(/((?:^|-)[a-z])/g, x => x.toUpperCase())] = o[key];
}
return capitalized;
},
// Detect the toString encoding from the request headers content-type
// enhance if further content types need to be non utf8 encoded.
detectEncoding: request => typeof request.headers['content-type'] === 'string' && request.headers['content-type'].includes('multipart/form-data') ? 'binary' : 'utf8',
createDefaultApiKey() {
return createHash('md5').digest('hex');
},
createUniqueId() {
return cuid();
},
};