/
Content.ts
75 lines (65 loc) · 2.19 KB
/
Content.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Content
*/
import { Descriptor, DescriptorJSON } from "./Descriptor";
import { Item, ItemJSON } from "./Item";
/**
* Serialized [[Content]] JSON representation.
* @public
*/
export interface ContentJSON {
descriptor: DescriptorJSON;
contentSet: ItemJSON[];
}
/**
* A data structure that contains the [[Descriptor]] and a list of [[Item]]
* objects which are based on that descriptor.
*
* @public
*/
export class Content {
/** Descriptor used to create the content */
public readonly descriptor: Descriptor;
/** Content items */
public readonly contentSet: Item[];
/** Create a new [[Content]] instance */
public constructor(descriptor: Descriptor, items: Item[]) {
this.descriptor = descriptor;
this.contentSet = items;
}
/** Serialize this object to JSON */
public toJSON(): ContentJSON {
return {
descriptor: this.descriptor.toJSON(),
contentSet: this.contentSet.map((item: Item) => item.toJSON()),
};
}
/** Deserialize [[Content]] from JSON */
public static fromJSON(json: ContentJSON | string | undefined): Content | undefined {
if (!json) {
return undefined;
}
if (typeof json === "string") {
return JSON.parse(json, (key, value) => Content.reviver(key, value));
}
const descriptor = Descriptor.fromJSON(json.descriptor);
if (!descriptor) {
return undefined;
}
const contentSet = json.contentSet.map((itemJson: ItemJSON) => Item.fromJSON(itemJson)).filter<Item>((item): item is Item => item !== undefined);
return new Content(descriptor, contentSet);
}
/**
* Reviver function that can be used as a second argument for
* `JSON.parse` method when parsing Content objects.
*
* @internal
*/
public static reviver(key: string, value: any): any {
return key === "" ? Content.fromJSON(value) : value;
}
}