-
Notifications
You must be signed in to change notification settings - Fork 15
/
path.js
45 lines (39 loc) · 1.15 KB
/
path.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
const jp = require('jsonpath');
function createNestedObject(object, keys, defaultValue) {
const nestedObject = object;
if (keys.length === 1) {
nestedObject[keys[0]] = defaultValue;
} else {
const key = keys.shift();
nestedObject[key] = createNestedObject(typeof nestedObject[key] === 'undefined' ? {} : nestedObject[key], keys, defaultValue);
}
return nestedObject;
}
function applyJsonPath(object, path = '$') {
if (typeof object === 'object' && object !== null) {
return jp.value(object, path) || {};
}
return object;
}
function applyInputPath(object, path) {
return applyJsonPath(object, path);
}
function applyOutputPath(object, path) {
return applyJsonPath(object, path);
}
// TODO: use a lib to implement reference paths
function applyResultPath(object, path = '$', value) {
const regex = /[^$.[\]]+/g; // regexp to split the reference paths
if (path === '$') {
return value; // return output
}
if (path === null) {
return object; // return input
}
return Object.assign({}, object, createNestedObject({}, path.match(regex), value));
}
module.exports = {
applyInputPath,
applyOutputPath,
applyResultPath,
};