-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (52 loc) · 1.92 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
import snakeCase from 'lodash/snakeCase'
import camelCase from 'lodash/camelCase'
import kebabCase from 'lodash/kebabCase'
import isPlainObject from 'lodash/isPlainObject'
import isObject from 'lodash/isObject'
import isArray from 'lodash/isArray'
const uuidValidate = function (value) {
const regex = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
return regex.test(value);
};
const mapKeysDeep = function (obj, fn) {
if (isArray(obj)) {
return obj.map((item) => {
return mapKeysDeep(item, fn);
});
}
if (isPlainObject(obj)) {
return Object.keys(obj).reduce((accumulator, key) => {
const value = obj[key];
const newKey = uuidValidate(key) ? key : fn(key);
accumulator[newKey] = isObject(value) ? mapKeysDeep(value, fn) : value;
return accumulator;
}, {});
}
return obj;
};
function createRequestModify(modifier) {
return async (request, options) => {
if (options.body && !(options.body instanceof FormData)) {
const body = JSON.parse(options.body);
const convertedBody = mapKeysDeep(body, modifier);
return new Request(request, { body: JSON.stringify(convertedBody) });
}
};
}
function createResponseModify(modifier) {
return async (input, options, response) => {
try {
const body = await response.json();
const convertedBody = mapKeysDeep(body, modifier);
return new Response(JSON.stringify(convertedBody), response);
} catch (e) {
return;
}
};
}
export const requestToSnakeCase = createRequestModify(snakeCase);
export const requestToCamelCase = createRequestModify(camelCase);
export const requestToKebabCase = createRequestModify(kebabCase);
export const responseToSnakeCase = createResponseModify(snakeCase);
export const responseToCamelCase = createResponseModify(camelCase);
export const responseToKebabCase = createResponseModify(kebabCase);