-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
query_helper.ts
110 lines (95 loc) · 2.48 KB
/
query_helper.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
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
import type { Context, RDF } from "../rdf.ts";
import type { Property, Schema } from "../schema/mod.ts";
import { encode } from "../encoder.ts";
import type { Entity } from "./types.ts";
export class QueryHelper {
private readonly entity: Entity;
private readonly schema: Schema;
private readonly context: Context;
private readonly variableInitCounter: number;
private quads?: RDF.Quad[];
private variableQuads?: RDF.Quad[];
constructor(
entity: Entity,
schema: Schema,
context: Context,
variableInitCounter = 0,
) {
this.entity = entity;
this.schema = schema;
this.context = context;
this.variableInitCounter = variableInitCounter;
}
getQuads() {
if (!this.quads) {
this.quads = encode(
this.entity,
this.schema,
this.context,
this.variableInitCounter,
);
}
return this.quads;
}
getVariableQuads() {
if (!this.variableQuads) {
this.variableQuads = encode(
this.getEntityWithReplacedVariables(),
this.schema,
this.context,
this.variableInitCounter,
);
}
return this.variableQuads;
}
getDeleteQuads() {
return this.getVariableQuads().filter(
(quad) => quad.object.termType === "Variable",
);
}
getInsertQuads() {
return this.getQuads();
}
getWhereQuads() {
return this.getVariableQuads();
}
private getEntityWithReplacedVariables() {
return this.replaceVariables(this.entity, this.schema);
}
private replaceVariables(entity: Entity, schema: Schema) {
return Object.keys(entity).reduce((output, key) => {
const value = entity[key];
if (key === "$id") {
output.$id = value;
return output;
}
if (key === "$type") {
output.$type = value;
return output;
}
const property = schema[key] as Property;
if (!property) {
throw new Error("Unknown field '${key}' detected in entity");
}
if (!property["@context"]) {
output[key] = null;
return output;
}
if (property["@array"]) {
if (value.length === 0) {
output[key] = null;
} else {
output[key] = value.map((subEntity: Entity) =>
this.replaceVariables(subEntity, property["@context"]!)
);
}
} else {
output[key] = this.replaceVariables(
value as Entity,
property["@context"],
);
}
return output;
}, {} as Entity);
}
}