-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.ts
79 lines (66 loc) · 1.96 KB
/
utils.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
76
77
78
79
import xsd from "../namespaces/xsd.ts";
import type {
Property,
PropertyPrototype,
Schema,
SchemaPrototype,
} from "./schema.ts";
export const expandSchema = (schemaPrototype: SchemaPrototype) => {
const expandArray = <T extends string>(stringOrStrings: T | readonly T[]) => {
return Array.isArray(stringOrStrings) ? stringOrStrings : [stringOrStrings];
};
const expandSchemaProperty = (
stringOrProperty: string | PropertyPrototype,
) => {
if (typeof stringOrProperty === "string") {
return {
"@id": stringOrProperty,
"@type": xsd.string,
};
}
const property = stringOrProperty;
if (!property["@id"]) {
throw new Error(`Invalid schema, "@id" key for property missing`);
}
const validKeys = [
"@context",
"@id",
"@type",
"@array",
"@optional",
"@multilang",
] as const;
const baseProperty: Record<string, unknown> = {
"@id": "",
};
const expandedProperty = Object.keys(property).reduce((acc, key) => {
if (key === "@context") {
acc[key] = expandSchema(property[key]!);
} else if (validKeys.includes(key as keyof PropertyPrototype)) {
acc[key] = property[key as keyof PropertyPrototype] as unknown;
}
return acc;
}, baseProperty);
if (!baseProperty["@type"] && !baseProperty["@context"]) {
baseProperty["@type"] = xsd.string;
}
return expandedProperty as Property;
};
const baseSchema: Schema = {
"@type": [],
};
return Object.keys(schemaPrototype).reduce((acc, key) => {
if (key === "@type") {
acc[key] = expandArray(schemaPrototype[key]);
} else {
acc[key] = expandSchemaProperty(
schemaPrototype[key] as string | PropertyPrototype,
);
}
return acc;
}, baseSchema);
};
export const getSchemaProperties = (schema: Schema) => {
const { "@type": _ommitedType, ...properties } = schema;
return properties as Record<string, Property>;
};