MCPcopy Index your code
hub / github.com/atomicdata-dev/atomic-data-browser / parseJsonADResource

Function parseJsonADResource

lib/src/parse.ts:9–70  ·  view source on GitHub ↗
(
  jsonObject: JSONObject,
  resource: Resource,
  /** Pass a Store if you want to add the parsed resources to it */
  store?: Store,
)

Source from the content-addressed store, hash-verified

7 * Also adds it to the store, if you pass a `store`.
8 */
9export function parseJsonADResource(
10 jsonObject: JSONObject,
11 resource: Resource,
12 /** Pass a Store if you want to add the parsed resources to it */
13 store?: Store,
14): Resource {
15 try {
16 for (const key in jsonObject) {
17 if (key == '@id') {
18 const subject = jsonObject['@id'];
19 if (typeof subject !== 'string') {
20 throw new Error("'@id' field must be a string");
21 }
22 if (
23 resource.getSubject() !== 'undefined' &&
24 resource.getSubject() !== unknownSubject &&
25 subject !== resource.getSubject()
26 ) {
27 throw new Error(
28 `Resource has wrong subject in @id. Received subject was ${subject}, expected ${resource.getSubject()}.`,
29 );
30 }
31 resource.setSubject(subject);
32 continue;
33 }
34 const value = jsonObject[key];
35 try {
36 // Resource values can be either strings (URLs) or full Resources, which in turn can be either Anonymous (no @id) or Named (with an @id)
37 if (isArray(value)) {
38 const newarr = value.map(val =>
39 parseJsonAdResourceValue(store, val, resource, key),
40 );
41 resource.setUnsafe(key, newarr);
42 } else if (typeof value === 'string') {
43 resource.setUnsafe(key, value);
44 } else if (typeof value === 'number') {
45 resource.setUnsafe(key, value);
46 } else if (typeof value === 'boolean') {
47 resource.setUnsafe(key, value);
48 } else {
49 const subject = parseJsonAdResourceValue(store, value, resource, key);
50 resource.setUnsafe(key, subject);
51 }
52 } catch (e) {
53 throw new Error(
54 `Failed creating value ${value} for key ${key} in resource ${resource.getSubject()}. ${
55 e.message
56 }`,
57 );
58 }
59 }
60 resource.loading == false;
61 store && store.addResource(resource);
62 } catch (e) {
63 e.message = 'Failed parsing JSON ' + e.message;
64 resource.setError(e);
65 resource.loading == false;
66 store && store.addResource(resource);

Callers 4

fetchResourceFunction · 0.90
parseJsonAdResourceValueFunction · 0.85
parseJsonADArrayFunction · 0.85
valToResourceFunction · 0.85

Calls 7

isArrayFunction · 0.85
parseJsonAdResourceValueFunction · 0.85
getSubjectMethod · 0.80
setSubjectMethod · 0.80
setUnsafeMethod · 0.80
addResourceMethod · 0.80
setErrorMethod · 0.80

Tested by

no test coverage detected