-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
235 lines (195 loc) · 5.96 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
const jsonpatcher = require('jsonpatch');
const traverseIterator = require('traverse-json');
const isPromise = require('is-promise');
const {
JSONPATCH_SEP,
JSONPATCH_OPS,
} = require('./constants');
const tap = require('./tap');
const parseIterator = (iterator) => {
if (Array.isArray(iterator)) {
iterator = iterator[Symbol.iterator]();
}
return iterator.next ? (extra) => iterator.next(extra) : iterator;
};
const parseOptions = (opts) => typeof opts !== 'object' ? ({ test: opts }) : { ...opts };
/**
* Patch definition acording to the [jsonpatch standard](http://jsonpatch.com/)
* @callback MutanPatch
* @param {("remove"|"replace")} op Patch operation
* @param {any} value
*/
/**
* @callback MutantPatcher
* @param {MutanPatch|MutanPatch[]} patches
*/
/**
* @callback MutantProcess
* @param {MutationPatcher} mutate
* @param {any} value
* @param {string} path
* @param {any} result
*/
/**
* @typedef {Array} MutantJsonEntry
* @prop {string} 0 [JSONPointer](https://tools.ietf.org/html/rfc6901)
* @prop {any} 1 Value
*/
/**
* @typedef {Object} MutantOptions
* @prop {Boolean} [recursive=true] enable/disable nested arrays and objects recursion
* @prop {Boolean} [nested=false] also emit nested array or objects
* @prop {Boolean} [step=1] the step to increment, default 1
* @prop {String|Function|RegeExp} [test=false] regexp, string [minimatch](https://www.npmjs.com/package/minimatch) or function to filter properties
* @prop {Boolean} [once=false] Stops when applies the first mutation
* @prop {Boolean} [promises=true] Processing promises taking the resolved as part of the result
* @prop {Boolean} [promise=false] Forces to return a promise even if no promises detected
* @prop {Array<MutationJsonEntry>|Iterable|Iterator} [iterator] Iterator default [traverse-json](https://github.com/rubeniskov/traverse-json)
* @prop {Function} [patcher] Patcher function
*/
/**
* Iterates through the given iterator and applies mutation
* whereas the iterator entry returns. Also works with promises.
* The iteratee must return an entry of [path, value].
*
* @param {any} target
* @param {MutantProcess} process
* @param {MutantOptions} opts
* @example
*
* ### Working with promises
*
* ```javascript
* const mutateJson = require('mutant-json');
*
* const recursiveObjectPromises = {
* foo: 0,
* nested: Promise.resolve({
* depth: 1,
* nested: Promise.resolve({
* depth: 2,
* nested: Promise.resolve({
* depth: 3,
* nested: Promise.resolve({
* depth: 4,
* }),
* }),
* }),
* }),
* bar: 1,
* };
*
* const actual = await mutateJson(recursiveObjectPromises, (mutate, value) => {
* mutate({
* value: value * 2,
* });
* });
*
* console.log(actual);
* ```
*
* ### Output
* ```
* {
* foo: 0,
* nested: {
* depth: 2,
* nested: {
* depth: 4,
* nested: {
* depth: 6,
* nested: {
* depth: 8,
* },
* },
* },
* },
* bar: 2,
* }
* ```
*/
const mutantJson = (target, process, opts) => {
if (isPromise(target)) {
return target.then((res) => mutantJson(res, process, opts));
}
const {
once = false,
promises = true,
promise = false,
iterator = traverseIterator(target, opts),
patcher = (target, patch) => jsonpatcher.apply_patch(target, [patch]),
} = parseOptions(opts);
const iteratee = parseIterator(iterator);
if (typeof process !== 'function') {
throw new Error('mutant-json: Process param must be defined and be a function');
}
const next = (extra) => {
const { value: entry = [], done } = extra ? iteratee(extra[0], extra[1]) : iteratee();
if (done) return { done };
if (!Array.isArray(entry) || entry.length < 2) {
throw new Error('mutant-json: Unexpected entry format, iterator must return a entry object [path: string, value: any]');
}
return { entry, done };
};
const applyPatches = (patch, path, result) => {
if (isPromise(patch)) {
return patch.then((res) => applyPatches(res, path, result));
}
if (!patch) return;
const parsedPatch = { op: JSONPATCH_OPS[0], ...patch, path };
if (!JSONPATCH_OPS.includes(parsedPatch.op)) {
throw new Error(`mutant-json: Unexpected patch operation "${parsedPatch.op}"`);
}
if ((path && path[0] !== JSONPATCH_SEP)) {
throw new Error(`mutant-json: JSONPointer must starts with a slash "${JSONPATCH_SEP}" (or be an empty string)!`);
}
const patched = patcher(result, parsedPatch);
return {
result: patched,
extra: parsedPatch.op !== 'remove'
&& parsedPatch.value !== null
&& typeof parsedPatch.value === 'object'
? [parsedPatch.path, tap(patched, parsedPatch.path)]
: undefined,
};
};
const processMutation = (value, path, target) => {
let ret;
const presult = process((patch) => {
ret = applyPatches(patch, path, target);
}, value, path, target);
if (isPromise(presult)) {
return presult.then(() => ret);
}
return ret;
};
const traverse = (result, extra, mutated) => {
if (mutated && once) return result;
const { entry, done } = next(extra);
if (done) return result;
const [ entryPath, entryValue ] = entry;
if (promises && isPromise(entryValue)) {
return entryValue.then((value) => {
return traverse(patcher(result, {
op: 'replace',
path: entryPath,
value,
}), [entryPath, value]);
});
}
const processResult = processMutation(entryValue, entryPath, result);
if (isPromise(processResult)) {
return processResult.then(({ result, extra }) => traverse(result, extra, true));
}
if (processResult) {
const { result, extra } = processResult;
return traverse(result, extra, true);
}
return traverse(result);
};
if (promise) {
return Promise.resolve(traverse(target));
}
return traverse(target);
};
module.exports = mutantJson;