@coasys/ad4m 0.10.1-release-candidate-3-test-2 → 0.10.1-release-candidate-4-debug-strings
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +105 -6
- package/lib/index.js +106 -7
- package/lib/src/language/Language.d.ts +3 -0
- package/lib/src/model/Ad4mModel.js +11 -5
- package/lib/src/perspectives/PerspectiveClient.js +1 -1
- package/lib/src/runtime/RuntimeClient.d.ts +3 -0
- package/lib/src/runtime/RuntimeClient.js +30 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +9 -0
- package/lib/src/runtime/RuntimeResolver.js +54 -0
- package/lib/src/schema.gql +10 -0
- package/lib/src/typeDefs.js +10 -0
- package/package.json +1 -2
- package/src/language/Language.ts +6 -2
- package/src/model/Ad4mModel.ts +13 -6
- package/src/perspectives/PerspectiveClient.ts +1 -1
- package/src/runtime/RuntimeClient.ts +33 -0
- package/src/runtime/RuntimeResolver.ts +34 -0
- package/lib/src/subject/Ad4mModel.d.ts +0 -550
- package/lib/src/subject/Ad4mModel.js +0 -956
- package/lib/src/subject/SDNADecorators.d.ts +0 -188
- package/lib/src/subject/SDNADecorators.js +0 -360
- package/lib/src/subject/Subject.d.ts +0 -25
- package/lib/src/subject/Subject.js +0 -188
- package/lib/src/subject/SubjectEntity.d.ts +0 -185
- package/lib/src/subject/SubjectEntity.js +0 -591
- package/lib/src/subject/decorators.d.ts +0 -496
- package/lib/src/subject/decorators.js +0 -683
- package/lib/src/subject/util.d.ts +0 -12
- package/lib/src/subject/util.js +0 -73
- package/yarn-error.log +0 -90
|
@@ -1,956 +0,0 @@
|
|
|
1
|
-
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
5
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
-
};
|
|
7
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
-
};
|
|
12
|
-
var _Ad4mModel_baseExpression, _Ad4mModel_subjectClassName, _Ad4mModel_source, _Ad4mModel_perspective;
|
|
13
|
-
import { Literal } from "../Literal";
|
|
14
|
-
import { Link } from "../links/Links";
|
|
15
|
-
import { makeRandomPrologAtom } from "./decorators";
|
|
16
|
-
import { singularToPlural } from "./util";
|
|
17
|
-
function capitalize(word) {
|
|
18
|
-
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
19
|
-
}
|
|
20
|
-
function buildSourceQuery(source) {
|
|
21
|
-
// Constrains the query to instances that have the provided source
|
|
22
|
-
if (!source)
|
|
23
|
-
return "";
|
|
24
|
-
return `triple("${source}", "ad4m://has_child", Base)`;
|
|
25
|
-
}
|
|
26
|
-
// todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
|
|
27
|
-
function buildAuthorAndTimestampQuery() {
|
|
28
|
-
// Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
|
|
29
|
-
return `
|
|
30
|
-
findall(
|
|
31
|
-
[T, A],
|
|
32
|
-
link(Base, _, _, T, A),
|
|
33
|
-
AllLinks
|
|
34
|
-
),
|
|
35
|
-
sort(AllLinks, SortedLinks),
|
|
36
|
-
SortedLinks = [[Timestamp, Author]|_]
|
|
37
|
-
`;
|
|
38
|
-
}
|
|
39
|
-
function buildPropertiesQuery(properties) {
|
|
40
|
-
// Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
|
|
41
|
-
// Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
|
|
42
|
-
// an Expression in JSON literal, or the direct literal value if it is a simple literal
|
|
43
|
-
// If no properties are provided, all are included
|
|
44
|
-
return `
|
|
45
|
-
findall([PropertyName, PropertyValue, Resolve], (
|
|
46
|
-
% Constrain to specified properties if provided
|
|
47
|
-
${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
|
|
48
|
-
resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
|
|
49
|
-
), Properties)
|
|
50
|
-
`;
|
|
51
|
-
}
|
|
52
|
-
function buildCollectionsQuery(collections) {
|
|
53
|
-
// Gets the name and array of values for all (or some) collections on a Ad4mModel instance
|
|
54
|
-
// If no collections are provided, all are included
|
|
55
|
-
return `
|
|
56
|
-
findall([CollectionName, CollectionValues], (
|
|
57
|
-
% Constrain to specified collections if provided
|
|
58
|
-
${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
|
|
59
|
-
|
|
60
|
-
collection(SubjectClass, CollectionName),
|
|
61
|
-
collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
|
|
62
|
-
), Collections)
|
|
63
|
-
`;
|
|
64
|
-
}
|
|
65
|
-
function buildWhereQuery(where = {}) {
|
|
66
|
-
// Constrains the query to instances that match the provided where conditions
|
|
67
|
-
function formatValue(value) {
|
|
68
|
-
// Wrap strings in quotes
|
|
69
|
-
return typeof value === "string" ? `"${value}"` : value;
|
|
70
|
-
}
|
|
71
|
-
return Object.entries(where)
|
|
72
|
-
.map(([key, value]) => {
|
|
73
|
-
const isSpecial = ["author", "timestamp"].includes(key);
|
|
74
|
-
const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
|
|
75
|
-
// const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
|
|
76
|
-
const field = capitalize(key);
|
|
77
|
-
// Handle direct array values (for IN conditions)
|
|
78
|
-
if (Array.isArray(value)) {
|
|
79
|
-
const formattedValues = value.map((v) => formatValue(v)).join(", ");
|
|
80
|
-
if (isSpecial)
|
|
81
|
-
return `member(${field}, [${formattedValues}])`;
|
|
82
|
-
else
|
|
83
|
-
return `${getter}, member(Value${key}, [${formattedValues}])`;
|
|
84
|
-
}
|
|
85
|
-
// Handle operation object
|
|
86
|
-
if (typeof value === "object" && value !== null) {
|
|
87
|
-
const { not, between, lt, lte, gt, gte } = value;
|
|
88
|
-
// Handle NOT operation
|
|
89
|
-
if (not !== undefined) {
|
|
90
|
-
if (Array.isArray(not)) {
|
|
91
|
-
// NOT IN array
|
|
92
|
-
const formattedValues = not.map((v) => formatValue(v)).join(", ");
|
|
93
|
-
if (isSpecial)
|
|
94
|
-
return `\\+ member(${field}, [${formattedValues}])`;
|
|
95
|
-
else
|
|
96
|
-
return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
|
|
97
|
-
}
|
|
98
|
-
else {
|
|
99
|
-
// NOT EQUAL
|
|
100
|
-
if (isSpecial)
|
|
101
|
-
return `${field} \\= ${formatValue(not)}`;
|
|
102
|
-
else
|
|
103
|
-
return `${getter}, Value${key} \\= ${formatValue(not)}`;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
// Handle BETWEEN
|
|
107
|
-
if (between !== undefined && Array.isArray(between) && between.length === 2) {
|
|
108
|
-
if (isSpecial)
|
|
109
|
-
return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
|
|
110
|
-
else
|
|
111
|
-
return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
|
|
112
|
-
}
|
|
113
|
-
// Handle lt, lte, gt, & gte operations
|
|
114
|
-
const operators = [
|
|
115
|
-
{ value: lt, symbol: "<" },
|
|
116
|
-
{ value: lte, symbol: "=<" },
|
|
117
|
-
{ value: gt, symbol: ">" },
|
|
118
|
-
{ value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
|
|
119
|
-
];
|
|
120
|
-
for (const { value, symbol } of operators) {
|
|
121
|
-
if (value !== undefined)
|
|
122
|
-
return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
// Default to direct equality
|
|
126
|
-
if (isSpecial)
|
|
127
|
-
return `${field} = ${formatValue(value)}`;
|
|
128
|
-
else
|
|
129
|
-
return `${getter}, Value${key} = ${formatValue(value)}`;
|
|
130
|
-
})
|
|
131
|
-
.join(", ");
|
|
132
|
-
}
|
|
133
|
-
function buildCountQuery(count) {
|
|
134
|
-
return count ? "length(UnsortedInstances, TotalCount)" : "";
|
|
135
|
-
}
|
|
136
|
-
function buildOrderQuery(order) {
|
|
137
|
-
if (!order)
|
|
138
|
-
return "SortedInstances = UnsortedInstances";
|
|
139
|
-
const [propertyName, direction] = Object.entries(order)[0];
|
|
140
|
-
return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
|
|
141
|
-
}
|
|
142
|
-
function buildOffsetQuery(offset) {
|
|
143
|
-
if (!offset || offset < 0)
|
|
144
|
-
return "InstancesWithOffset = SortedInstances";
|
|
145
|
-
return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
|
|
146
|
-
}
|
|
147
|
-
function buildLimitQuery(limit) {
|
|
148
|
-
if (!limit || limit < 0)
|
|
149
|
-
return "AllInstances = InstancesWithOffset";
|
|
150
|
-
return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
|
|
151
|
-
}
|
|
152
|
-
/**
|
|
153
|
-
* Base class for defining data models in AD4M.
|
|
154
|
-
*
|
|
155
|
-
* @description
|
|
156
|
-
* Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
|
|
157
|
-
* Each model instance is represented as a subgraph in the perspective, with properties and collections
|
|
158
|
-
* mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
|
|
159
|
-
* instances based on their properties and relationships.
|
|
160
|
-
*
|
|
161
|
-
* Key concepts:
|
|
162
|
-
* - Each model instance has a unique base expression that serves as its identifier
|
|
163
|
-
* - Properties are stored as links with predicates defined by the `through` option
|
|
164
|
-
* - Collections represent one-to-many relationships as sets of links
|
|
165
|
-
* - Queries are translated to Prolog for efficient graph pattern matching
|
|
166
|
-
* - Changes are tracked through the perspective's subscription system
|
|
167
|
-
*
|
|
168
|
-
* @example
|
|
169
|
-
* ```typescript
|
|
170
|
-
* // Define a recipe model
|
|
171
|
-
* @ModelOptions({ name: "Recipe" })
|
|
172
|
-
* class Recipe extends Ad4mModel {
|
|
173
|
-
* // Required property with literal value
|
|
174
|
-
* @Property({
|
|
175
|
-
* through: "recipe://name",
|
|
176
|
-
* resolveLanguage: "literal"
|
|
177
|
-
* })
|
|
178
|
-
* name: string = "";
|
|
179
|
-
*
|
|
180
|
-
* // Optional property with custom initial value
|
|
181
|
-
* @Optional({
|
|
182
|
-
* through: "recipe://status",
|
|
183
|
-
* initial: "recipe://draft"
|
|
184
|
-
* })
|
|
185
|
-
* status: string = "";
|
|
186
|
-
*
|
|
187
|
-
* // Read-only computed property
|
|
188
|
-
* @ReadOnly({
|
|
189
|
-
* through: "recipe://rating",
|
|
190
|
-
* getter: `
|
|
191
|
-
* findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
|
|
192
|
-
* sum_list(Ratings, Sum),
|
|
193
|
-
* length(Ratings, Count),
|
|
194
|
-
* Value is Sum / Count
|
|
195
|
-
* `
|
|
196
|
-
* })
|
|
197
|
-
* averageRating: number = 0;
|
|
198
|
-
*
|
|
199
|
-
* // Collection of ingredients
|
|
200
|
-
* @Collection({ through: "recipe://ingredient" })
|
|
201
|
-
* ingredients: string[] = [];
|
|
202
|
-
*
|
|
203
|
-
* // Collection of comments that are instances of another model
|
|
204
|
-
* @Collection({
|
|
205
|
-
* through: "recipe://comment",
|
|
206
|
-
* where: { isInstance: Comment }
|
|
207
|
-
* })
|
|
208
|
-
* comments: Comment[] = [];
|
|
209
|
-
* }
|
|
210
|
-
*
|
|
211
|
-
* // Create and save a new recipe
|
|
212
|
-
* const recipe = new Recipe(perspective);
|
|
213
|
-
* recipe.name = "Chocolate Cake";
|
|
214
|
-
* recipe.ingredients = ["flour", "sugar", "cocoa"];
|
|
215
|
-
* await recipe.save();
|
|
216
|
-
*
|
|
217
|
-
* // Query recipes in different ways
|
|
218
|
-
* // Get all recipes
|
|
219
|
-
* const allRecipes = await Recipe.findAll(perspective);
|
|
220
|
-
*
|
|
221
|
-
* // Find recipes with specific criteria
|
|
222
|
-
* const desserts = await Recipe.findAll(perspective, {
|
|
223
|
-
* where: {
|
|
224
|
-
* status: "recipe://published",
|
|
225
|
-
* averageRating: { gt: 4 }
|
|
226
|
-
* },
|
|
227
|
-
* order: { name: "ASC" },
|
|
228
|
-
* limit: 10
|
|
229
|
-
* });
|
|
230
|
-
*
|
|
231
|
-
* // Use the fluent query builder
|
|
232
|
-
* const popularRecipes = await Recipe.query(perspective)
|
|
233
|
-
* .where({ averageRating: { gt: 4.5 } })
|
|
234
|
-
* .order({ averageRating: "DESC" })
|
|
235
|
-
* .limit(5)
|
|
236
|
-
* .get();
|
|
237
|
-
*
|
|
238
|
-
* // Subscribe to real-time updates
|
|
239
|
-
* await Recipe.query(perspective)
|
|
240
|
-
* .where({ status: "recipe://cooking" })
|
|
241
|
-
* .subscribe(recipes => {
|
|
242
|
-
* console.log("Currently being cooked:", recipes);
|
|
243
|
-
* });
|
|
244
|
-
*
|
|
245
|
-
* // Paginate results
|
|
246
|
-
* const { results, totalCount, pageNumber } = await Recipe.query(perspective)
|
|
247
|
-
* .where({ status: "recipe://published" })
|
|
248
|
-
* .paginate(10, 1);
|
|
249
|
-
* ```
|
|
250
|
-
*/
|
|
251
|
-
export class Ad4mModel {
|
|
252
|
-
static async getClassName(perspective) {
|
|
253
|
-
// Get or create the cache for this class
|
|
254
|
-
let classCache = this.classNamesByClass.get(this);
|
|
255
|
-
if (!classCache) {
|
|
256
|
-
classCache = {};
|
|
257
|
-
this.classNamesByClass.set(this, classCache);
|
|
258
|
-
}
|
|
259
|
-
// Get or create the cached name for this perspective
|
|
260
|
-
const perspectiveID = perspective.uuid;
|
|
261
|
-
if (!classCache[perspectiveID]) {
|
|
262
|
-
classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
|
|
263
|
-
}
|
|
264
|
-
return classCache[perspectiveID];
|
|
265
|
-
}
|
|
266
|
-
/**
|
|
267
|
-
* Constructs a new model instance.
|
|
268
|
-
*
|
|
269
|
-
* @param perspective - The perspective where this model will be stored
|
|
270
|
-
* @param baseExpression - Optional unique identifier for this instance
|
|
271
|
-
* @param source - Optional source expression this instance is linked to
|
|
272
|
-
*
|
|
273
|
-
* @example
|
|
274
|
-
* ```typescript
|
|
275
|
-
* // Create a new recipe with auto-generated base expression
|
|
276
|
-
* const recipe = new Recipe(perspective);
|
|
277
|
-
*
|
|
278
|
-
* // Create with specific base expression
|
|
279
|
-
* const recipe = new Recipe(perspective, "recipe://chocolate-cake");
|
|
280
|
-
*
|
|
281
|
-
* // Create with source link
|
|
282
|
-
* const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
|
|
283
|
-
* ```
|
|
284
|
-
*/
|
|
285
|
-
constructor(perspective, baseExpression, source) {
|
|
286
|
-
_Ad4mModel_baseExpression.set(this, void 0);
|
|
287
|
-
_Ad4mModel_subjectClassName.set(this, void 0);
|
|
288
|
-
_Ad4mModel_source.set(this, void 0);
|
|
289
|
-
_Ad4mModel_perspective.set(this, void 0);
|
|
290
|
-
__classPrivateFieldSet(this, _Ad4mModel_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
|
|
291
|
-
__classPrivateFieldSet(this, _Ad4mModel_perspective, perspective, "f");
|
|
292
|
-
__classPrivateFieldSet(this, _Ad4mModel_source, source || "ad4m://self", "f");
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* Gets the base expression of the subject.
|
|
296
|
-
*/
|
|
297
|
-
get baseExpression() {
|
|
298
|
-
return __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f");
|
|
299
|
-
}
|
|
300
|
-
/**
|
|
301
|
-
* Protected getter for the perspective.
|
|
302
|
-
* Allows subclasses to access the perspective while keeping it private from external code.
|
|
303
|
-
*/
|
|
304
|
-
get perspective() {
|
|
305
|
-
return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
|
|
306
|
-
}
|
|
307
|
-
static async assignValuesToInstance(perspective, instance, values) {
|
|
308
|
-
// Map properties to object
|
|
309
|
-
const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
|
|
310
|
-
let finalValue = value;
|
|
311
|
-
// Resolve the value if necessary
|
|
312
|
-
if (resolve) {
|
|
313
|
-
let resolvedExpression = await perspective.getExpression(value);
|
|
314
|
-
if (resolvedExpression) {
|
|
315
|
-
finalValue = resolvedExpression.data;
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
return [name, finalValue];
|
|
319
|
-
})));
|
|
320
|
-
// Assign properties to instance
|
|
321
|
-
Object.assign(instance, propsObject);
|
|
322
|
-
}
|
|
323
|
-
async getData() {
|
|
324
|
-
// Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
|
|
325
|
-
const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
|
|
326
|
-
const fullQuery = `
|
|
327
|
-
Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
|
|
328
|
-
subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
|
|
329
|
-
${subQueries.join(", ")}
|
|
330
|
-
`;
|
|
331
|
-
const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
|
|
332
|
-
if (result?.[0]) {
|
|
333
|
-
const { Properties, Collections, Timestamp, Author } = result?.[0];
|
|
334
|
-
const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
|
|
335
|
-
await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
|
|
336
|
-
}
|
|
337
|
-
return this;
|
|
338
|
-
}
|
|
339
|
-
// Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
|
|
340
|
-
static async queryToProlog(perspective, query) {
|
|
341
|
-
const { source, properties, collections, where, order, offset, limit, count } = query;
|
|
342
|
-
const instanceQueries = [
|
|
343
|
-
buildAuthorAndTimestampQuery(),
|
|
344
|
-
buildSourceQuery(source),
|
|
345
|
-
buildPropertiesQuery(properties),
|
|
346
|
-
buildCollectionsQuery(collections),
|
|
347
|
-
buildWhereQuery(where),
|
|
348
|
-
];
|
|
349
|
-
const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
|
|
350
|
-
const fullQuery = `
|
|
351
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
352
|
-
subject_class("${await this.getClassName(perspective)}", SubjectClass),
|
|
353
|
-
instance(SubjectClass, Base),
|
|
354
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
355
|
-
), UnsortedInstances),
|
|
356
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
357
|
-
`;
|
|
358
|
-
return fullQuery;
|
|
359
|
-
}
|
|
360
|
-
static async instancesFromPrologResult(perspective, query, result) {
|
|
361
|
-
if (!result?.[0]?.AllInstances)
|
|
362
|
-
return { results: [], totalCount: 0 };
|
|
363
|
-
// Map results to instances
|
|
364
|
-
const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
|
|
365
|
-
const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
|
|
366
|
-
try {
|
|
367
|
-
const instance = new this(perspective, Base);
|
|
368
|
-
// Remove unrequested attributes from instance
|
|
369
|
-
if (requestedAttribtes.length) {
|
|
370
|
-
Object.keys(instance).forEach((key) => {
|
|
371
|
-
if (!requestedAttribtes.includes(key))
|
|
372
|
-
delete instance[key];
|
|
373
|
-
});
|
|
374
|
-
}
|
|
375
|
-
// Collect values to assign to instance
|
|
376
|
-
const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
|
|
377
|
-
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
378
|
-
return instance;
|
|
379
|
-
}
|
|
380
|
-
catch (error) {
|
|
381
|
-
console.error(`Failed to process instance ${Base}:`, error);
|
|
382
|
-
// Return null for failed instances - we'll filter these out below
|
|
383
|
-
return null;
|
|
384
|
-
}
|
|
385
|
-
}));
|
|
386
|
-
return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
|
|
387
|
-
}
|
|
388
|
-
/**
|
|
389
|
-
* Gets all instances of the model in the perspective that match the query params.
|
|
390
|
-
*
|
|
391
|
-
* @param perspective - The perspective to search in
|
|
392
|
-
* @param query - Optional query parameters to filter results
|
|
393
|
-
* @returns Array of matching models
|
|
394
|
-
*
|
|
395
|
-
* @example
|
|
396
|
-
* ```typescript
|
|
397
|
-
* // Get all recipes
|
|
398
|
-
* const allRecipes = await Recipe.findAll(perspective);
|
|
399
|
-
*
|
|
400
|
-
* // Get recipes with specific criteria
|
|
401
|
-
* const recipes = await Recipe.findAll(perspective, {
|
|
402
|
-
* where: {
|
|
403
|
-
* name: "Pasta",
|
|
404
|
-
* rating: { gt: 4 }
|
|
405
|
-
* },
|
|
406
|
-
* order: { createdAt: "DESC" },
|
|
407
|
-
* limit: 10
|
|
408
|
-
* });
|
|
409
|
-
* ```
|
|
410
|
-
*/
|
|
411
|
-
static async findAll(perspective, query = {}) {
|
|
412
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
413
|
-
const result = await perspective.infer(prologQuery);
|
|
414
|
-
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
415
|
-
return results;
|
|
416
|
-
}
|
|
417
|
-
/**
|
|
418
|
-
* Gets all instances with count of total matches without limit applied.
|
|
419
|
-
*
|
|
420
|
-
* @param perspective - The perspective to search in
|
|
421
|
-
* @param query - Optional query parameters to filter results
|
|
422
|
-
* @returns Object containing results array and total count
|
|
423
|
-
*
|
|
424
|
-
* @example
|
|
425
|
-
* ```typescript
|
|
426
|
-
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
|
|
427
|
-
* where: { category: "Dessert" },
|
|
428
|
-
* limit: 10
|
|
429
|
-
* });
|
|
430
|
-
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
431
|
-
* ```
|
|
432
|
-
*/
|
|
433
|
-
static async findAllAndCount(perspective, query = {}) {
|
|
434
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
435
|
-
const result = await perspective.infer(prologQuery);
|
|
436
|
-
return await this.instancesFromPrologResult(perspective, query, result);
|
|
437
|
-
}
|
|
438
|
-
/**
|
|
439
|
-
* Helper function for pagination with explicit page size and number.
|
|
440
|
-
*
|
|
441
|
-
* @param perspective - The perspective to search in
|
|
442
|
-
* @param pageSize - Number of items per page
|
|
443
|
-
* @param pageNumber - Which page to retrieve (1-based)
|
|
444
|
-
* @param query - Optional additional query parameters
|
|
445
|
-
* @returns Paginated results with metadata
|
|
446
|
-
*
|
|
447
|
-
* @example
|
|
448
|
-
* ```typescript
|
|
449
|
-
* const page = await Recipe.paginate(perspective, 10, 1, {
|
|
450
|
-
* where: { category: "Main Course" }
|
|
451
|
-
* });
|
|
452
|
-
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
453
|
-
* ```
|
|
454
|
-
*/
|
|
455
|
-
static async paginate(perspective, pageSize, pageNumber, query) {
|
|
456
|
-
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
457
|
-
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
458
|
-
const result = await perspective.infer(prologQuery);
|
|
459
|
-
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
460
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
461
|
-
}
|
|
462
|
-
static async countQueryToProlog(perspective, query = {}) {
|
|
463
|
-
const { source, where } = query;
|
|
464
|
-
const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
|
|
465
|
-
const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
|
|
466
|
-
const fullQuery = `
|
|
467
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
468
|
-
subject_class("${await this.getClassName(perspective)}", SubjectClass),
|
|
469
|
-
instance(SubjectClass, Base),
|
|
470
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
471
|
-
), UnsortedInstances),
|
|
472
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
473
|
-
`;
|
|
474
|
-
return fullQuery;
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* Gets a count of all matching instances.
|
|
478
|
-
*
|
|
479
|
-
* @param perspective - The perspective to search in
|
|
480
|
-
* @param query - Optional query parameters to filter results
|
|
481
|
-
* @returns Total count of matching entities
|
|
482
|
-
*
|
|
483
|
-
* @example
|
|
484
|
-
* ```typescript
|
|
485
|
-
* const totalRecipes = await Recipe.count(perspective);
|
|
486
|
-
* const activeRecipes = await Recipe.count(perspective, {
|
|
487
|
-
* where: { status: "active" }
|
|
488
|
-
* });
|
|
489
|
-
* ```
|
|
490
|
-
*/
|
|
491
|
-
static async count(perspective, query = {}) {
|
|
492
|
-
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
493
|
-
return result?.[0]?.TotalCount || 0;
|
|
494
|
-
}
|
|
495
|
-
async setProperty(key, value) {
|
|
496
|
-
const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
|
|
497
|
-
if (setters && setters.length > 0) {
|
|
498
|
-
const actions = eval(setters[0].Setter);
|
|
499
|
-
const resolveLanguageResults = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_resolve_language(C, "${key}", Language)`);
|
|
500
|
-
let resolveLanguage;
|
|
501
|
-
if (resolveLanguageResults && resolveLanguageResults.length > 0) {
|
|
502
|
-
resolveLanguage = resolveLanguageResults[0].Language;
|
|
503
|
-
}
|
|
504
|
-
if (resolveLanguage) {
|
|
505
|
-
value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
|
|
506
|
-
}
|
|
507
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }]);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
async setCollectionSetter(key, value) {
|
|
511
|
-
let collectionSetters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
|
|
512
|
-
if (!collectionSetters)
|
|
513
|
-
collectionSetters = [];
|
|
514
|
-
if (collectionSetters.length > 0) {
|
|
515
|
-
const actions = eval(collectionSetters[0].Setter);
|
|
516
|
-
if (value) {
|
|
517
|
-
if (Array.isArray(value)) {
|
|
518
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })));
|
|
519
|
-
}
|
|
520
|
-
else {
|
|
521
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }]);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
async setCollectionAdder(key, value) {
|
|
527
|
-
let adders = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
|
|
528
|
-
if (!adders)
|
|
529
|
-
adders = [];
|
|
530
|
-
if (adders.length > 0) {
|
|
531
|
-
const actions = eval(adders[0].Adder);
|
|
532
|
-
if (value) {
|
|
533
|
-
if (Array.isArray(value)) {
|
|
534
|
-
await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }])));
|
|
535
|
-
}
|
|
536
|
-
else {
|
|
537
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }]);
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
async setCollectionRemover(key, value) {
|
|
543
|
-
let removers = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
|
|
544
|
-
if (!removers)
|
|
545
|
-
removers = [];
|
|
546
|
-
if (removers.length > 0) {
|
|
547
|
-
const actions = eval(removers[0].Remover);
|
|
548
|
-
if (value) {
|
|
549
|
-
if (Array.isArray(value)) {
|
|
550
|
-
await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }])));
|
|
551
|
-
}
|
|
552
|
-
else {
|
|
553
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }]);
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* Saves the model instance to the perspective.
|
|
560
|
-
* Creates a new instance with the base expression and links it to the source.
|
|
561
|
-
*
|
|
562
|
-
* @throws Will throw if instance creation, linking, or updating fails
|
|
563
|
-
*
|
|
564
|
-
* @example
|
|
565
|
-
* ```typescript
|
|
566
|
-
* const recipe = new Recipe(perspective);
|
|
567
|
-
* recipe.name = "Spaghetti";
|
|
568
|
-
* recipe.ingredients = ["pasta", "tomato sauce"];
|
|
569
|
-
* await recipe.save();
|
|
570
|
-
* ```
|
|
571
|
-
*/
|
|
572
|
-
async save() {
|
|
573
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
|
|
574
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").add(new Link({ source: __classPrivateFieldGet(this, _Ad4mModel_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }));
|
|
575
|
-
await this.update();
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* Updates the model instance's properties and collections.
|
|
579
|
-
*
|
|
580
|
-
* @throws Will throw if property setting or collection updates fail
|
|
581
|
-
*
|
|
582
|
-
* @example
|
|
583
|
-
* ```typescript
|
|
584
|
-
* const recipe = await Recipe.findAll(perspective)[0];
|
|
585
|
-
* recipe.rating = 5;
|
|
586
|
-
* recipe.ingredients.push("garlic");
|
|
587
|
-
* await recipe.update();
|
|
588
|
-
* ```
|
|
589
|
-
*/
|
|
590
|
-
async update() {
|
|
591
|
-
__classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
|
|
592
|
-
const entries = Object.entries(this);
|
|
593
|
-
for (const [key, value] of entries) {
|
|
594
|
-
if (value !== undefined && value !== null) {
|
|
595
|
-
if (value?.action) {
|
|
596
|
-
switch (value.action) {
|
|
597
|
-
case "setter":
|
|
598
|
-
await this.setCollectionSetter(key, value.value);
|
|
599
|
-
break;
|
|
600
|
-
case "adder":
|
|
601
|
-
await this.setCollectionAdder(key, value.value);
|
|
602
|
-
break;
|
|
603
|
-
case "remover":
|
|
604
|
-
await this.setCollectionRemover(key, value.value);
|
|
605
|
-
default:
|
|
606
|
-
await this.setCollectionSetter(key, value.value);
|
|
607
|
-
break;
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
else if (Array.isArray(value) && value.length > 0) {
|
|
611
|
-
await this.setCollectionSetter(key, value);
|
|
612
|
-
}
|
|
613
|
-
else if (value !== undefined && value !== null && value !== "") {
|
|
614
|
-
await this.setProperty(key, value);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
await this.getData();
|
|
619
|
-
}
|
|
620
|
-
/**
|
|
621
|
-
* Gets the model instance with all properties and collections populated.
|
|
622
|
-
*
|
|
623
|
-
* @returns The populated model instance
|
|
624
|
-
* @throws Will throw if data retrieval fails
|
|
625
|
-
*
|
|
626
|
-
* @example
|
|
627
|
-
* ```typescript
|
|
628
|
-
* const recipe = new Recipe(perspective, existingId);
|
|
629
|
-
* await recipe.get();
|
|
630
|
-
* console.log(recipe.name, recipe.ingredients);
|
|
631
|
-
* ```
|
|
632
|
-
*/
|
|
633
|
-
async get() {
|
|
634
|
-
__classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
|
|
635
|
-
return await this.getData();
|
|
636
|
-
}
|
|
637
|
-
/**
|
|
638
|
-
* Deletes the model instance from the perspective.
|
|
639
|
-
*
|
|
640
|
-
* @throws Will throw if removal fails
|
|
641
|
-
*
|
|
642
|
-
* @example
|
|
643
|
-
* ```typescript
|
|
644
|
-
* const recipe = await Recipe.findAll(perspective)[0];
|
|
645
|
-
* await recipe.delete();
|
|
646
|
-
* ```
|
|
647
|
-
*/
|
|
648
|
-
async delete() {
|
|
649
|
-
await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
|
|
650
|
-
}
|
|
651
|
-
/**
|
|
652
|
-
* Creates a query builder for fluent query construction.
|
|
653
|
-
*
|
|
654
|
-
* @param perspective - The perspective to query
|
|
655
|
-
* @param query - Optional initial query parameters
|
|
656
|
-
* @returns A new query builder instance
|
|
657
|
-
*
|
|
658
|
-
* @example
|
|
659
|
-
* ```typescript
|
|
660
|
-
* const recipes = await Recipe.query(perspective)
|
|
661
|
-
* .where({ category: "Dessert" })
|
|
662
|
-
* .order({ rating: "DESC" })
|
|
663
|
-
* .limit(5)
|
|
664
|
-
* .run();
|
|
665
|
-
*
|
|
666
|
-
* // With real-time updates
|
|
667
|
-
* await Recipe.query(perspective)
|
|
668
|
-
* .where({ status: "cooking" })
|
|
669
|
-
* .subscribeAndRun(recipes => {
|
|
670
|
-
* console.log("Currently cooking:", recipes);
|
|
671
|
-
* });
|
|
672
|
-
* ```
|
|
673
|
-
*/
|
|
674
|
-
static query(perspective, query) {
|
|
675
|
-
return new ModelQueryBuilder(perspective, this, query);
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
_Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
|
|
679
|
-
Ad4mModel.classNamesByClass = new WeakMap();
|
|
680
|
-
/** Query builder for Ad4mModel queries.
|
|
681
|
-
* Allows building queries with a fluent interface and either running them once
|
|
682
|
-
* or subscribing to updates.
|
|
683
|
-
*
|
|
684
|
-
* @example
|
|
685
|
-
* ```typescript
|
|
686
|
-
* const builder = Recipe.query(perspective)
|
|
687
|
-
* .where({ category: "Dessert" })
|
|
688
|
-
* .order({ rating: "DESC" })
|
|
689
|
-
* .limit(10);
|
|
690
|
-
*
|
|
691
|
-
* // Run once
|
|
692
|
-
* const recipes = await builder.run();
|
|
693
|
-
*
|
|
694
|
-
* // Or subscribe to updates
|
|
695
|
-
* await builder.subscribeAndRun(recipes => {
|
|
696
|
-
* console.log("Updated recipes:", recipes);
|
|
697
|
-
* });
|
|
698
|
-
* ```
|
|
699
|
-
*/
|
|
700
|
-
export class ModelQueryBuilder {
|
|
701
|
-
constructor(perspective, ctor, query) {
|
|
702
|
-
this.queryParams = {};
|
|
703
|
-
this.perspective = perspective;
|
|
704
|
-
this.ctor = ctor;
|
|
705
|
-
if (query)
|
|
706
|
-
this.queryParams = query;
|
|
707
|
-
}
|
|
708
|
-
/**
|
|
709
|
-
* Adds where conditions to the query.
|
|
710
|
-
*
|
|
711
|
-
* @param conditions - The conditions to filter by
|
|
712
|
-
* @returns The query builder for chaining
|
|
713
|
-
*
|
|
714
|
-
* @example
|
|
715
|
-
* ```typescript
|
|
716
|
-
* .where({
|
|
717
|
-
* category: "Dessert",
|
|
718
|
-
* rating: { gt: 4 },
|
|
719
|
-
* tags: ["vegan", "quick"],
|
|
720
|
-
* published: true
|
|
721
|
-
* })
|
|
722
|
-
* ```
|
|
723
|
-
*/
|
|
724
|
-
where(conditions) {
|
|
725
|
-
this.queryParams.where = conditions;
|
|
726
|
-
return this;
|
|
727
|
-
}
|
|
728
|
-
/**
|
|
729
|
-
* Sets the order for the query results.
|
|
730
|
-
*
|
|
731
|
-
* @param orderBy - The ordering criteria
|
|
732
|
-
* @returns The query builder for chaining
|
|
733
|
-
*
|
|
734
|
-
* @example
|
|
735
|
-
* ```typescript
|
|
736
|
-
* .order({ createdAt: "DESC" })
|
|
737
|
-
* ```
|
|
738
|
-
*/
|
|
739
|
-
order(orderBy) {
|
|
740
|
-
this.queryParams.order = orderBy;
|
|
741
|
-
return this;
|
|
742
|
-
}
|
|
743
|
-
/**
|
|
744
|
-
* Sets the maximum number of results to return.
|
|
745
|
-
*
|
|
746
|
-
* @param limit - Maximum number of results
|
|
747
|
-
* @returns The query builder for chaining
|
|
748
|
-
*
|
|
749
|
-
* @example
|
|
750
|
-
* ```typescript
|
|
751
|
-
* .limit(10)
|
|
752
|
-
* ```
|
|
753
|
-
*/
|
|
754
|
-
limit(limit) {
|
|
755
|
-
this.queryParams.limit = limit;
|
|
756
|
-
return this;
|
|
757
|
-
}
|
|
758
|
-
/**
|
|
759
|
-
* Sets the number of results to skip.
|
|
760
|
-
*
|
|
761
|
-
* @param offset - Number of results to skip
|
|
762
|
-
* @returns The query builder for chaining
|
|
763
|
-
*
|
|
764
|
-
* @example
|
|
765
|
-
* ```typescript
|
|
766
|
-
* .offset(20) // Skip first 20 results
|
|
767
|
-
* ```
|
|
768
|
-
*/
|
|
769
|
-
offset(offset) {
|
|
770
|
-
this.queryParams.offset = offset;
|
|
771
|
-
return this;
|
|
772
|
-
}
|
|
773
|
-
/**
|
|
774
|
-
* Sets the source filter for the query.
|
|
775
|
-
*
|
|
776
|
-
* @param source - The source to filter by
|
|
777
|
-
* @returns The query builder for chaining
|
|
778
|
-
*
|
|
779
|
-
* @example
|
|
780
|
-
* ```typescript
|
|
781
|
-
* .source("ad4m://self")
|
|
782
|
-
* ```
|
|
783
|
-
*/
|
|
784
|
-
source(source) {
|
|
785
|
-
this.queryParams.source = source;
|
|
786
|
-
return this;
|
|
787
|
-
}
|
|
788
|
-
/**
|
|
789
|
-
* Specifies which properties to include in the results.
|
|
790
|
-
*
|
|
791
|
-
* @param properties - Array of property names to include
|
|
792
|
-
* @returns The query builder for chaining
|
|
793
|
-
*
|
|
794
|
-
* @example
|
|
795
|
-
* ```typescript
|
|
796
|
-
* .properties(["name", "description", "rating"])
|
|
797
|
-
* ```
|
|
798
|
-
*/
|
|
799
|
-
properties(properties) {
|
|
800
|
-
this.queryParams.properties = properties;
|
|
801
|
-
return this;
|
|
802
|
-
}
|
|
803
|
-
/**
|
|
804
|
-
* Specifies which collections to include in the results.
|
|
805
|
-
*
|
|
806
|
-
* @param collections - Array of collection names to include
|
|
807
|
-
* @returns The query builder for chaining
|
|
808
|
-
*
|
|
809
|
-
* @example
|
|
810
|
-
* ```typescript
|
|
811
|
-
* .collections(["ingredients", "steps"])
|
|
812
|
-
* ```
|
|
813
|
-
*/
|
|
814
|
-
collections(collections) {
|
|
815
|
-
this.queryParams.collections = collections;
|
|
816
|
-
return this;
|
|
817
|
-
}
|
|
818
|
-
/**
|
|
819
|
-
* Executes the query once and returns the results.
|
|
820
|
-
*
|
|
821
|
-
* @returns Array of matching entities
|
|
822
|
-
*
|
|
823
|
-
* @example
|
|
824
|
-
* ```typescript
|
|
825
|
-
* const recipes = await Recipe.query(perspective)
|
|
826
|
-
* .where({ category: "Dessert" })
|
|
827
|
-
* .get();
|
|
828
|
-
* ```
|
|
829
|
-
*/
|
|
830
|
-
async get() {
|
|
831
|
-
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
|
|
832
|
-
const result = await this.perspective.infer(query);
|
|
833
|
-
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
834
|
-
return results;
|
|
835
|
-
}
|
|
836
|
-
/**
|
|
837
|
-
* Subscribes to the query and receives updates when results change.
|
|
838
|
-
* Also returns initial results immediately.
|
|
839
|
-
*
|
|
840
|
-
* @param callback - Function to call with updated results
|
|
841
|
-
* @returns Initial results array
|
|
842
|
-
*
|
|
843
|
-
* @example
|
|
844
|
-
* ```typescript
|
|
845
|
-
* await Recipe.query(perspective)
|
|
846
|
-
* .where({ status: "cooking" })
|
|
847
|
-
* .subscribe(recipes => {
|
|
848
|
-
* console.log("Currently cooking:", recipes);
|
|
849
|
-
* });
|
|
850
|
-
* ```
|
|
851
|
-
*/
|
|
852
|
-
async subscribe(callback) {
|
|
853
|
-
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
|
|
854
|
-
const subscription = await this.perspective.subscribeInfer(query);
|
|
855
|
-
const processResults = async (result) => {
|
|
856
|
-
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
857
|
-
callback(results);
|
|
858
|
-
};
|
|
859
|
-
subscription.onResult(processResults);
|
|
860
|
-
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, subscription.result);
|
|
861
|
-
return results;
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* Gets the total count of matching entities.
|
|
865
|
-
*
|
|
866
|
-
* @returns Total count
|
|
867
|
-
*
|
|
868
|
-
* @example
|
|
869
|
-
* ```typescript
|
|
870
|
-
* const totalDesserts = await Recipe.query(perspective)
|
|
871
|
-
* .where({ category: "Dessert" })
|
|
872
|
-
* .count();
|
|
873
|
-
* ```
|
|
874
|
-
*/
|
|
875
|
-
async count() {
|
|
876
|
-
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams);
|
|
877
|
-
const result = await this.perspective.infer(query);
|
|
878
|
-
return result?.[0]?.TotalCount || 0;
|
|
879
|
-
}
|
|
880
|
-
/**
|
|
881
|
-
* Subscribes to count updates for matching entities.
|
|
882
|
-
*
|
|
883
|
-
* @param callback - Function to call with updated count
|
|
884
|
-
* @returns Initial count
|
|
885
|
-
*
|
|
886
|
-
* @example
|
|
887
|
-
* ```typescript
|
|
888
|
-
* await Recipe.query(perspective)
|
|
889
|
-
* .where({ status: "active" })
|
|
890
|
-
* .countSubscribe(count => {
|
|
891
|
-
* console.log("Active items:", count);
|
|
892
|
-
* });
|
|
893
|
-
* ```
|
|
894
|
-
*/
|
|
895
|
-
async countSubscribe(callback) {
|
|
896
|
-
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams);
|
|
897
|
-
const subscription = await this.perspective.subscribeInfer(query);
|
|
898
|
-
const processResults = async (result) => {
|
|
899
|
-
const newCount = result?.[0]?.TotalCount || 0;
|
|
900
|
-
callback(newCount);
|
|
901
|
-
};
|
|
902
|
-
subscription.onResult(processResults);
|
|
903
|
-
return subscription.result?.[0]?.TotalCount || 0;
|
|
904
|
-
}
|
|
905
|
-
/**
|
|
906
|
-
* Gets a page of results with pagination metadata.
|
|
907
|
-
*
|
|
908
|
-
* @param pageSize - Number of items per page
|
|
909
|
-
* @param pageNumber - Which page to retrieve (1-based)
|
|
910
|
-
* @returns Paginated results with metadata
|
|
911
|
-
*
|
|
912
|
-
* @example
|
|
913
|
-
* ```typescript
|
|
914
|
-
* const page = await Recipe.query(perspective)
|
|
915
|
-
* .where({ category: "Main" })
|
|
916
|
-
* .paginate(10, 1);
|
|
917
|
-
* console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
|
|
918
|
-
* ```
|
|
919
|
-
*/
|
|
920
|
-
async paginate(pageSize, pageNumber) {
|
|
921
|
-
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
922
|
-
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery);
|
|
923
|
-
const result = await this.perspective.infer(prologQuery);
|
|
924
|
-
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
|
|
925
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
926
|
-
}
|
|
927
|
-
/**
|
|
928
|
-
* Subscribes to paginated results updates.
|
|
929
|
-
*
|
|
930
|
-
* @param pageSize - Number of items per page
|
|
931
|
-
* @param pageNumber - Which page to retrieve (1-based)
|
|
932
|
-
* @param callback - Function to call with updated pagination results
|
|
933
|
-
* @returns Initial pagination results
|
|
934
|
-
*
|
|
935
|
-
* @example
|
|
936
|
-
* ```typescript
|
|
937
|
-
* await Recipe.query(perspective)
|
|
938
|
-
* .where({ category: "Main" })
|
|
939
|
-
* .paginateSubscribe(10, 1, page => {
|
|
940
|
-
* console.log("Updated page:", page.results);
|
|
941
|
-
* });
|
|
942
|
-
* ```
|
|
943
|
-
*/
|
|
944
|
-
async paginateSubscribe(pageSize, pageNumber, callback) {
|
|
945
|
-
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
946
|
-
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery);
|
|
947
|
-
const subscription = await this.perspective.subscribeInfer(prologQuery);
|
|
948
|
-
const processResults = async (r) => {
|
|
949
|
-
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
|
|
950
|
-
callback({ results, totalCount, pageSize, pageNumber });
|
|
951
|
-
};
|
|
952
|
-
subscription.onResult(processResults);
|
|
953
|
-
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, subscription.result));
|
|
954
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
955
|
-
}
|
|
956
|
-
}
|