-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.ts
60 lines (56 loc) · 1.71 KB
/
json.ts
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 type { Tree } from 'nx/src/config/tree';
import { parseJson, serializeJson } from 'nx/src/utils/json';
import type { JsonParseOptions, JsonSerializeOptions } from 'nx/src/utils/json';
/**
* Reads a json file, removes all comments and parses JSON.
*
* @param tree - file system tree
* @param path - file path
* @param options - Optional JSON Parse Options
*/
export function readJson<T extends object = any>(
tree: Tree,
path: string,
options?: JsonParseOptions
): T {
if (!tree.exists(path)) {
throw new Error(`Cannot find ${path}`);
}
try {
return parseJson(tree.read(path, 'utf-8'), options);
} catch (e) {
throw new Error(`Cannot parse ${path}: ${e.message}`);
}
}
/**
* Writes a JSON value to the file system tree
* @param tree File system tree
* @param path Path of JSON file in the Tree
* @param value Serializable value to write
* @param options Optional JSON Serialize Options
*/
export function writeJson<T extends object = object>(
tree: Tree,
path: string,
value: T,
options?: JsonSerializeOptions
): void {
tree.write(path, serializeJson(value, options));
}
/**
* Updates a JSON value to the file system tree
*
* @param tree File system tree
* @param path Path of JSON file in the Tree
* @param updater Function that maps the current value of a JSON document to a new value to be written to the document
* @param options Optional JSON Parse and Serialize Options
*/
export function updateJson<T extends object = any, U extends object = T>(
tree: Tree,
path: string,
updater: (value: T) => U,
options?: JsonParseOptions & JsonSerializeOptions
): void {
const updatedValue = updater(readJson(tree, path, options));
writeJson(tree, path, updatedValue, options);
}