@appweaver/data 2.5.0 → 2.6.0
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/README.md +4 -2
- package/config.d.ts +1 -0
- package/config.js +1 -0
- package/database/database-config.d.ts +9 -0
- package/database/database-config.js +56 -1
- package/database/database-error.d.ts +8 -0
- package/database/database-error.js +18 -0
- package/database/prisma-database.js +16 -5
- package/database/setup-database.d.ts +23 -0
- package/database/setup-database.js +59 -0
- package/database/sqlserver-extension.js +21 -107
- package/database/telemetry-extension.d.ts +10 -0
- package/database/telemetry-extension.js +52 -0
- package/export/export-service.js +4 -0
- package/factory/create-model.d.ts +1 -1
- package/factory/create-model.js +75 -4
- package/factory/create-service.js +8 -0
- package/index.d.ts +2 -0
- package/index.js +5 -0
- package/internal.d.ts +2 -0
- package/internal.js +3 -1
- package/module.js +6 -3
- package/package.json +3 -3
- package/resource/resource-service.d.ts +32 -7
- package/resource/resource-service.js +244 -35
- package/resource/schemas/resource-filter-schema.d.ts +8 -0
- package/resource/schemas/resource-filter-schema.js +40 -1
- package/resource/schemas/resource-sort-schema.js +10 -0
- package/resource/utils/cursor-util.d.ts +13 -0
- package/resource/utils/cursor-util.js +21 -0
- package/resource/utils/filter-util.d.ts +9 -0
- package/resource/utils/filter-util.js +17 -0
- package/resource/utils/sort-util.d.ts +14 -0
- package/resource/utils/sort-util.js +1 -0
- package/resource/utils/where-util.d.ts +20 -0
- package/resource/utils/where-util.js +210 -0
- package/seeder/create-seeder.d.ts +3 -0
- package/seeder/create-seeder.js +1 -1
- package/seeder/seeder.d.ts +4 -2
- package/seeder/seeder.js +56 -23
- package/spatial/geo-schema.d.ts +22 -0
- package/spatial/geo-schema.js +60 -0
- package/spatial/spatial-config.d.ts +21 -0
- package/spatial/spatial-config.js +52 -0
- package/spatial/spatial-engine.d.ts +78 -0
- package/spatial/spatial-engine.js +232 -0
- package/spatial/spatial-extension.d.ts +10 -0
- package/spatial/spatial-extension.js +100 -0
- package/spatial/spatial-service.d.ts +54 -0
- package/spatial/spatial-service.js +213 -0
- package/spatial/utils/box-util.d.ts +31 -0
- package/spatial/utils/box-util.js +62 -0
- package/timeseries/database-time-series.js +2 -13
- package/timeseries/timescale-config.d.ts +1 -1
- package/timeseries/timescale-time-series.d.ts +6 -4
- package/timeseries/timescale-time-series.js +46 -19
- package/utils/schema-util.d.ts +8 -0
- package/utils/schema-util.js +22 -0
- package/utils/write-data-util.d.ts +22 -0
- package/utils/write-data-util.js +144 -0
|
@@ -15,6 +15,8 @@ const relation_util_1 = require("./utils/relation-util");
|
|
|
15
15
|
const cursor_util_1 = require("./utils/cursor-util");
|
|
16
16
|
const filter_util_1 = require("./utils/filter-util");
|
|
17
17
|
const sort_util_1 = require("./utils/sort-util");
|
|
18
|
+
const where_util_1 = require("./utils/where-util");
|
|
19
|
+
const spatial_service_1 = require("../spatial/spatial-service");
|
|
18
20
|
const logger = (0, common_1.createLogger)('resource');
|
|
19
21
|
class ResourceService {
|
|
20
22
|
modelName;
|
|
@@ -84,10 +86,11 @@ class ResourceService {
|
|
|
84
86
|
if (!access) {
|
|
85
87
|
throw new common_1.ResourceError(common_1.ErrorCode.ResourceForbidden, `${this._client.name} access is forbidden`, { model: this._client.name, action: 'find' });
|
|
86
88
|
}
|
|
89
|
+
const projected = this.projectResource(resource);
|
|
87
90
|
this._events.emitResourceEvent(this._client.name, 'find', {
|
|
88
|
-
current:
|
|
91
|
+
current: projected
|
|
89
92
|
});
|
|
90
|
-
return
|
|
93
|
+
return projected;
|
|
91
94
|
}
|
|
92
95
|
/**
|
|
93
96
|
* Queries a page of resources matching the provided filter. The filter is
|
|
@@ -101,8 +104,9 @@ class ResourceService {
|
|
|
101
104
|
* `_not`, `_nor`), comparison (`_eq`, `_ne`, `_gt`, `_gte`, `_lt`, `_lte`,
|
|
102
105
|
* `_in`, `_nin`, `_between`, `_like`, `_ilike`, `_starts`, `_ends`,
|
|
103
106
|
* `_contains`, `_exists`), list (`_has`, `_hasSome`, `_hasEvery`,
|
|
104
|
-
* `_isEmpty`),
|
|
105
|
-
*
|
|
107
|
+
* `_isEmpty`), relation (`_some`, `_every`, `_none`), and geo field
|
|
108
|
+
* (`_near`, `_within`, `_withinBox`, `_intersects`) operators, as well as
|
|
109
|
+
* plain field values. Its `searchText` property, if present, is passed to
|
|
106
110
|
* {@link ResourceService.textSearchQuery} instead of being matched as a
|
|
107
111
|
* field.
|
|
108
112
|
* - `page` The one-based page number of results to return, ignored when a
|
|
@@ -114,7 +118,8 @@ class ResourceService {
|
|
|
114
118
|
* `{ createdAt: 'desc', id: 'asc' }`). Both forms support the fields of the
|
|
115
119
|
* included to-one relations, given with a dot notation (`author.createdAt`)
|
|
116
120
|
* or as a nested object (`{ author: { createdAt: 'desc' } }`) (default:
|
|
117
|
-
* `-createdAt`).
|
|
121
|
+
* `-createdAt`). A geo field, alone, sorts by the distance from the point
|
|
122
|
+
* of its `_near` filter.
|
|
118
123
|
* - `cursor` The cursor of the page to return, as issued in the `nextCursor`
|
|
119
124
|
* or `prevCursor` of an earlier response, which also carries the direction
|
|
120
125
|
* the page runs in. Takes precedence over `page`.
|
|
@@ -122,15 +127,22 @@ class ResourceService {
|
|
|
122
127
|
* of every one of them (default: `true`).
|
|
123
128
|
* @return {Promise<QueryResponse<Object>>} The paged query response containing
|
|
124
129
|
* the returned resources, the count of the returned items, the cursors of the
|
|
125
|
-
* adjacent pages, and the total count unless it was opted out of.
|
|
130
|
+
* adjacent pages, and the total count unless it was opted out of. A resource
|
|
131
|
+
* matched by the `_near` filter of a geo field carries its distance in meters
|
|
132
|
+
* as `<field>Distance`.
|
|
126
133
|
* @throws {@link ResourceError} `RESOURCE_INVALID_SORT` if the sort input names
|
|
127
134
|
* a field that cannot be sorted by, `RESOURCE_INVALID_CURSOR` if the cursor
|
|
128
|
-
* was issued for another filter or sort order,
|
|
129
|
-
* a database error.
|
|
135
|
+
* was issued for another filter or sort order, a {@link SpatialError} on an
|
|
136
|
+
* invalid geo field filter, and a {@link DatabaseError} on a database error.
|
|
130
137
|
*/
|
|
131
138
|
async query(options = {}) {
|
|
132
139
|
const { filter = {}, page = 1, size = 50, sort = '-createdAt', cursor, totalCount = true } = options;
|
|
133
|
-
const
|
|
140
|
+
const distanceSort = this.distanceSort(sort);
|
|
141
|
+
if (distanceSort) {
|
|
142
|
+
return this.queryByDistance(distanceSort, options);
|
|
143
|
+
}
|
|
144
|
+
const distances = new Map();
|
|
145
|
+
const query = await this.queryConditions('query', filter, distances);
|
|
134
146
|
const includeRelations = (0, relation_util_1.mapRelationInclusions)(this._client.name, 'query');
|
|
135
147
|
const orderBy = (0, sort_util_1.mapStableSortValues)(sort, this._client.name, 'query');
|
|
136
148
|
// Binding to the mapped query rather than the filter also invalidates a
|
|
@@ -177,14 +189,16 @@ class ResourceService {
|
|
|
177
189
|
// The page a cursor was followed from always exists
|
|
178
190
|
const hasNext = backward || hasMore;
|
|
179
191
|
const hasPrev = backward ? hasMore : !!decodedCursor || page > 1;
|
|
192
|
+
setDistances(resources, distances);
|
|
193
|
+
const items = resources.map((resource) => this.projectResource(resource));
|
|
180
194
|
this._events.emitResourceEvent(this._client.name, 'query', {
|
|
181
|
-
current:
|
|
195
|
+
current: items
|
|
182
196
|
});
|
|
183
197
|
return {
|
|
184
198
|
resultCount: resources.length,
|
|
185
199
|
totalCount: count ?? null,
|
|
186
200
|
...(0, cursor_util_1.pageCursors)(resources, fingerprint, hasNext, hasPrev),
|
|
187
|
-
items
|
|
201
|
+
items
|
|
188
202
|
};
|
|
189
203
|
}
|
|
190
204
|
/**
|
|
@@ -207,31 +221,43 @@ class ResourceService {
|
|
|
207
221
|
* error.
|
|
208
222
|
*/
|
|
209
223
|
async single(filter = {}, sort = '-createdAt') {
|
|
210
|
-
const where = await this.queryConditions('query', filter);
|
|
211
224
|
const includeRelations = (0, relation_util_1.mapRelationInclusions)(this._client.name, 'find');
|
|
212
|
-
const
|
|
225
|
+
const distanceSort = this.distanceSort(sort);
|
|
226
|
+
const distances = new Map();
|
|
213
227
|
let resource;
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
});
|
|
228
|
+
if (distanceSort) {
|
|
229
|
+
const { ids } = await this.distanceOrderedIds(distanceSort, filter, distances);
|
|
230
|
+
resource = ids.length
|
|
231
|
+
? (await this.findByIds([ids[0]], includeRelations))[0]
|
|
232
|
+
: null;
|
|
220
233
|
}
|
|
221
|
-
|
|
222
|
-
|
|
234
|
+
else {
|
|
235
|
+
const where = await this.queryConditions('query', filter, distances);
|
|
236
|
+
const orderBy = (0, sort_util_1.mapStableSortValues)(sort, this._client.name, 'find');
|
|
237
|
+
try {
|
|
238
|
+
resource = await this._client.findFirst({
|
|
239
|
+
where,
|
|
240
|
+
include: includeRelations,
|
|
241
|
+
orderBy
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
catch (e) {
|
|
245
|
+
throw this.databaseError(e);
|
|
246
|
+
}
|
|
223
247
|
}
|
|
224
248
|
if (!resource) {
|
|
225
249
|
return null;
|
|
226
250
|
}
|
|
251
|
+
setDistances([resource], distances);
|
|
227
252
|
const access = await this.applyAccessCheck('find', resource);
|
|
228
253
|
if (!access) {
|
|
229
254
|
throw new common_1.ResourceError(common_1.ErrorCode.ResourceForbidden, `${this._client.name} access is forbidden`, { model: this._client.name, action: 'find' });
|
|
230
255
|
}
|
|
256
|
+
const projected = this.projectResource(resource);
|
|
231
257
|
this._events.emitResourceEvent(this._client.name, 'find', {
|
|
232
|
-
current:
|
|
258
|
+
current: projected
|
|
233
259
|
});
|
|
234
|
-
return
|
|
260
|
+
return projected;
|
|
235
261
|
}
|
|
236
262
|
/**
|
|
237
263
|
* Counts the resources matching the provided filter, applying the read
|
|
@@ -402,11 +428,12 @@ class ResourceService {
|
|
|
402
428
|
throw this.databaseError(e);
|
|
403
429
|
}
|
|
404
430
|
await this._cacheService.invalidateCache(this._client.name, 'create');
|
|
431
|
+
const projected = this.projectResource(resource);
|
|
405
432
|
this._events.emitResourceEvent(this._client.name, 'create', {
|
|
406
|
-
current:
|
|
433
|
+
current: projected
|
|
407
434
|
});
|
|
408
435
|
logger.debug({ model: this._client.name, id: resource.id }, 'Resource created');
|
|
409
|
-
return
|
|
436
|
+
return projected;
|
|
410
437
|
}
|
|
411
438
|
/**
|
|
412
439
|
* Updates an existing resource by its id. The current record is loaded with
|
|
@@ -534,11 +561,12 @@ class ResourceService {
|
|
|
534
561
|
throw this.databaseError(e, id);
|
|
535
562
|
}
|
|
536
563
|
await this.cleanupDeletedRecords(deleted);
|
|
564
|
+
const projected = this.projectResource(resource);
|
|
537
565
|
this._events.emitResourceEvent(this._client.name, 'delete', {
|
|
538
|
-
current:
|
|
566
|
+
current: projected
|
|
539
567
|
});
|
|
540
568
|
logger.debug({ model: this._client.name, id, softDelete }, 'Resource deleted');
|
|
541
|
-
return
|
|
569
|
+
return projected;
|
|
542
570
|
}
|
|
543
571
|
/**
|
|
544
572
|
* Creates many resources in a single transaction, one after another the same
|
|
@@ -608,6 +636,25 @@ class ResourceService {
|
|
|
608
636
|
}
|
|
609
637
|
});
|
|
610
638
|
}
|
|
639
|
+
/**
|
|
640
|
+
* Checks whether the current user may receive a resource event, i.e. on the
|
|
641
|
+
* realtime connection of the user, run as that user with `runAs`. Always
|
|
642
|
+
* granted for the calls run with internal access (see `withoutPolicies`).
|
|
643
|
+
*
|
|
644
|
+
* @param {ResourceEvent} event The action and the resource of the event.
|
|
645
|
+
* @return {Promise<boolean>} True if the user may receive the event.
|
|
646
|
+
*/
|
|
647
|
+
async checkEventAccess(event) {
|
|
648
|
+
if ((0, policy_util_1.arePoliciesSkipped)() || (await this.eventAccess(event))) {
|
|
649
|
+
return true;
|
|
650
|
+
}
|
|
651
|
+
logger.debug({
|
|
652
|
+
model: this._client.name,
|
|
653
|
+
action: event.action,
|
|
654
|
+
id: event.current?.id
|
|
655
|
+
}, 'Resource event denied by its policy');
|
|
656
|
+
return false;
|
|
657
|
+
}
|
|
611
658
|
/**
|
|
612
659
|
* Updates an existing resource the same way as {@link ResourceService.update},
|
|
613
660
|
* returning the state the resource had before the update along with the
|
|
@@ -677,15 +724,13 @@ class ResourceService {
|
|
|
677
724
|
}
|
|
678
725
|
await this._cacheService.invalidateCache(this._client.name, 'update');
|
|
679
726
|
await this.cleanupDeletedRecords(orphans);
|
|
680
|
-
|
|
681
|
-
previous: updateResource,
|
|
682
|
-
current: resource
|
|
683
|
-
});
|
|
684
|
-
logger.debug({ model: this._client.name, id }, 'Resource updated');
|
|
685
|
-
return {
|
|
727
|
+
const projected = {
|
|
686
728
|
previous: this.projectResource(updateResource),
|
|
687
729
|
current: this.projectResource(resource)
|
|
688
730
|
};
|
|
731
|
+
this._events.emitResourceEvent(this._client.name, 'update', projected);
|
|
732
|
+
logger.debug({ model: this._client.name, id }, 'Resource updated');
|
|
733
|
+
return projected;
|
|
689
734
|
}
|
|
690
735
|
/**
|
|
691
736
|
* Completes the data of a replacement with the updatable scalar fields it
|
|
@@ -790,6 +835,35 @@ class ResourceService {
|
|
|
790
835
|
async checkAccess(action, resource) {
|
|
791
836
|
return true;
|
|
792
837
|
}
|
|
838
|
+
/**
|
|
839
|
+
* Checks whether the current user may receive a resource event. By default
|
|
840
|
+
* the user must pass the {@link ResourceService.checkAccess} of a `find` of
|
|
841
|
+
* the resource, which must match the {@link ResourceService.readRestrictions}
|
|
842
|
+
* of the `find`. The restrictions are matched in memory, and by the database
|
|
843
|
+
* when they filter by a relation, so a deleted resource whose restrictions
|
|
844
|
+
* only the database can match is denied.
|
|
845
|
+
*
|
|
846
|
+
* @param {ResourceEvent} event The action and the resource of the event.
|
|
847
|
+
* @return {Promise<boolean>} True if the user may receive the event.
|
|
848
|
+
*/
|
|
849
|
+
async eventAccess(event) {
|
|
850
|
+
const resource = event.current;
|
|
851
|
+
if (!(await this.checkAccess('find', event.current))) {
|
|
852
|
+
return false;
|
|
853
|
+
}
|
|
854
|
+
const restrictions = await this.readRestrictions('find', resource.id);
|
|
855
|
+
const matched = (0, where_util_1.matchesWhere)(resource, restrictions);
|
|
856
|
+
if (matched !== undefined) {
|
|
857
|
+
return matched;
|
|
858
|
+
}
|
|
859
|
+
if (event.action === 'delete') {
|
|
860
|
+
return false;
|
|
861
|
+
}
|
|
862
|
+
const count = await this._client.count({
|
|
863
|
+
where: { AND: [{ id: resource.id }, restrictions] }
|
|
864
|
+
});
|
|
865
|
+
return count > 0;
|
|
866
|
+
}
|
|
793
867
|
/**
|
|
794
868
|
* Constructs a query object for performing a text search on resources in the
|
|
795
869
|
* database based on the provided search text. This method will transform the
|
|
@@ -847,14 +921,136 @@ class ResourceService {
|
|
|
847
921
|
*
|
|
848
922
|
* @internal
|
|
849
923
|
*/
|
|
850
|
-
async queryConditions(action, filter) {
|
|
924
|
+
async queryConditions(action, filter, distances) {
|
|
851
925
|
const restrictions = await this.applyReadRestrictions(action, filter);
|
|
852
926
|
const textSearch = this.extractTextSearchQuery(filter);
|
|
853
|
-
|
|
927
|
+
// The conditions of the geo fields are resolved first (see SpatialService),
|
|
928
|
+
// collecting the distances of their `_near` operators
|
|
929
|
+
const spatial = await (0, core_1.inject)(spatial_service_1.SpatialService, false)?.resolveFilter(filter, this._client.name);
|
|
930
|
+
spatial?.distances.forEach((byId, field) => distances?.set(field, byId));
|
|
931
|
+
const mappedFilter = (0, filter_util_1.mapQueryFilter)(spatial?.filter ?? filter, this._client.name);
|
|
854
932
|
return {
|
|
855
933
|
AND: [mappedFilter, textSearch, restrictions, ...this.liveFilters()]
|
|
856
934
|
};
|
|
857
935
|
}
|
|
936
|
+
/**
|
|
937
|
+
* Reads the sort by the distance of a geo field: the field alone, its
|
|
938
|
+
* records ordered by their distance from the point of its `_near` filter.
|
|
939
|
+
*
|
|
940
|
+
* @throws {ResourceError} `RESOURCE_INVALID_SORT` when the geo field is
|
|
941
|
+
* sorted by along other fields.
|
|
942
|
+
* @internal
|
|
943
|
+
*/
|
|
944
|
+
distanceSort(sort) {
|
|
945
|
+
const geo = (0, core_1.injectModel)(this._client.name, false)?.config.geo;
|
|
946
|
+
if (!geo || sort === undefined || sort === null) {
|
|
947
|
+
return undefined;
|
|
948
|
+
}
|
|
949
|
+
const entries = (0, sort_util_1.sortEntries)(sort);
|
|
950
|
+
const geoEntry = entries.find(([path]) => geo[path]);
|
|
951
|
+
if (!geoEntry) {
|
|
952
|
+
return undefined;
|
|
953
|
+
}
|
|
954
|
+
if (entries.length > 1) {
|
|
955
|
+
throw new common_1.ResourceError(common_1.ErrorCode.ResourceInvalidSort, `Sorting by the distance of '${geoEntry[0]}' takes no other sort field`, { field: geoEntry[0] });
|
|
956
|
+
}
|
|
957
|
+
return { field: geoEntry[0], direction: geoEntry[1] };
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Lists the ids of the records matching a filter, ordered by the distance of
|
|
961
|
+
* a geo field from the point of its `_near` filter, then by their id.
|
|
962
|
+
*
|
|
963
|
+
* @throws {ResourceError} `RESOURCE_INVALID_SORT` when the filter has no
|
|
964
|
+
* `_near` operator on the geo field.
|
|
965
|
+
* @internal
|
|
966
|
+
*/
|
|
967
|
+
async distanceOrderedIds(sort, filter, spatialDistances) {
|
|
968
|
+
const query = await this.queryConditions('query', filter, spatialDistances);
|
|
969
|
+
const distances = spatialDistances.get(sort.field);
|
|
970
|
+
if (!distances) {
|
|
971
|
+
throw new common_1.ResourceError(common_1.ErrorCode.ResourceInvalidSort, `Sorting by the distance of '${sort.field}' needs a _near filter on it`, { field: sort.field });
|
|
972
|
+
}
|
|
973
|
+
let records;
|
|
974
|
+
try {
|
|
975
|
+
records = await this._client.findMany({
|
|
976
|
+
where: query,
|
|
977
|
+
select: { id: true }
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
catch (e) {
|
|
981
|
+
throw this.databaseError(e);
|
|
982
|
+
}
|
|
983
|
+
const sign = sort.direction === 'desc' ? -1 : 1;
|
|
984
|
+
const ids = records
|
|
985
|
+
.map((record) => record.id)
|
|
986
|
+
.sort((a, b) => sign * (distances.get(a) - distances.get(b)) ||
|
|
987
|
+
(a === b ? 0 : a < b ? -1 : 1));
|
|
988
|
+
return { ids, query };
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Reads the records of a list of ids in its order.
|
|
992
|
+
*
|
|
993
|
+
* @internal
|
|
994
|
+
*/
|
|
995
|
+
async findByIds(ids, include) {
|
|
996
|
+
if (ids.length === 0) {
|
|
997
|
+
return [];
|
|
998
|
+
}
|
|
999
|
+
let records;
|
|
1000
|
+
try {
|
|
1001
|
+
records = await this._client.findMany({
|
|
1002
|
+
where: { id: { in: ids } },
|
|
1003
|
+
include
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
catch (e) {
|
|
1007
|
+
throw this.databaseError(e);
|
|
1008
|
+
}
|
|
1009
|
+
const byId = new Map(records.map((record) => [record.id, record]));
|
|
1010
|
+
return ids.map((id) => byId.get(id)).filter(Boolean);
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* Queries a page of the records ordered by the distance of a geo field, see
|
|
1014
|
+
* {@link ResourceService.query}. The matching ids are ordered in memory,
|
|
1015
|
+
* bounded by `spatial.maxCandidates`, then the records of the page are read.
|
|
1016
|
+
*
|
|
1017
|
+
* @internal
|
|
1018
|
+
*/
|
|
1019
|
+
async queryByDistance(sort, options) {
|
|
1020
|
+
const { filter = {}, page = 1, size = 50, cursor, totalCount = true } = options;
|
|
1021
|
+
const distances = new Map();
|
|
1022
|
+
const { ids, query } = await this.distanceOrderedIds(sort, filter, distances);
|
|
1023
|
+
const fingerprint = (0, cursor_util_1.queryFingerprint)(this._client.name, query, [
|
|
1024
|
+
{ [sort.field]: sort.direction }
|
|
1025
|
+
]);
|
|
1026
|
+
const decodedCursor = (0, cursor_util_1.decodeCursor)(cursor, fingerprint);
|
|
1027
|
+
let start = (page - 1) * size;
|
|
1028
|
+
let end = start + size;
|
|
1029
|
+
if (decodedCursor) {
|
|
1030
|
+
const index = ids.indexOf(decodedCursor.id);
|
|
1031
|
+
if (index < 0) {
|
|
1032
|
+
throw new common_1.ResourceError(common_1.ErrorCode.ResourceInvalidCursor, 'Invalid pagination cursor');
|
|
1033
|
+
}
|
|
1034
|
+
[start, end] = decodedCursor.backward
|
|
1035
|
+
? [Math.max(0, index - size), index]
|
|
1036
|
+
: [index + 1, index + 1 + size];
|
|
1037
|
+
}
|
|
1038
|
+
const pageIds = size > 0 ? ids.slice(start, end) : [];
|
|
1039
|
+
const resources = await this.findByIds(pageIds, (0, relation_util_1.mapRelationInclusions)(this._client.name, 'query'));
|
|
1040
|
+
const hasNext = end < ids.length;
|
|
1041
|
+
const hasPrev = start > 0;
|
|
1042
|
+
setDistances(resources, distances);
|
|
1043
|
+
const items = resources.map((resource) => this.projectResource(resource));
|
|
1044
|
+
this._events.emitResourceEvent(this._client.name, 'query', {
|
|
1045
|
+
current: items
|
|
1046
|
+
});
|
|
1047
|
+
return {
|
|
1048
|
+
resultCount: resources.length,
|
|
1049
|
+
totalCount: totalCount ? ids.length : null,
|
|
1050
|
+
...(0, cursor_util_1.pageCursors)(resources, fingerprint, hasNext, hasPrev),
|
|
1051
|
+
items
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
858
1054
|
/**
|
|
859
1055
|
* Removes the `searchText` property from the provided filter and converts it
|
|
860
1056
|
* into a text search query using
|
|
@@ -1058,3 +1254,16 @@ class ResourceService {
|
|
|
1058
1254
|
}
|
|
1059
1255
|
}
|
|
1060
1256
|
exports.ResourceService = ResourceService;
|
|
1257
|
+
/**
|
|
1258
|
+
* Sets the distance of each record from the point of the `_near` filter of a geo field, as its `<field>Distance`.
|
|
1259
|
+
*/
|
|
1260
|
+
function setDistances(resources, distances) {
|
|
1261
|
+
for (const [field, byId] of distances) {
|
|
1262
|
+
for (const resource of resources) {
|
|
1263
|
+
const distance = byId.get(resource.id);
|
|
1264
|
+
if (distance !== undefined) {
|
|
1265
|
+
resource[(0, common_1.distanceFieldName)(field)] = distance;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
@@ -2,6 +2,8 @@ import { TObject } from '@sinclair/typebox';
|
|
|
2
2
|
import { ResourceModel } from '@appweaver/common';
|
|
3
3
|
/** The schema name the shared field condition object is registered under. */
|
|
4
4
|
export declare const QUERY_CONDITION_SCHEMA_NAME = "QueryCondition";
|
|
5
|
+
/** The schema name the shared geo field condition object is registered under. */
|
|
6
|
+
export declare const GEO_CONDITION_SCHEMA_NAME = "GeoCondition";
|
|
5
7
|
/**
|
|
6
8
|
* Resolves the schema name the query filter of a model is registered under.
|
|
7
9
|
*
|
|
@@ -16,6 +18,12 @@ export declare const queryFilterName: (modelName: string) => string;
|
|
|
16
18
|
* are rejected by the request validation.
|
|
17
19
|
*/
|
|
18
20
|
export declare const QueryConditionSchema: TObject;
|
|
21
|
+
/**
|
|
22
|
+
* The shared schema of a geo field condition object, holding the spatial
|
|
23
|
+
* operators. Operators combined inside the same object must all match, and
|
|
24
|
+
* the distances are in meters.
|
|
25
|
+
*/
|
|
26
|
+
export declare const GeoConditionSchema: TObject;
|
|
19
27
|
/**
|
|
20
28
|
* Builds the query filter schema of a resource model, mirroring the WHERE part
|
|
21
29
|
* of a database query. Every filterable field of the model is declared
|
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.QueryConditionSchema = exports.queryFilterName = exports.QUERY_CONDITION_SCHEMA_NAME = void 0;
|
|
3
|
+
exports.GeoConditionSchema = exports.QueryConditionSchema = exports.queryFilterName = exports.GEO_CONDITION_SCHEMA_NAME = exports.QUERY_CONDITION_SCHEMA_NAME = void 0;
|
|
4
4
|
exports.buildQueryFilterSchema = buildQueryFilterSchema;
|
|
5
5
|
exports.registerQueryFilterSchemas = registerQueryFilterSchemas;
|
|
6
6
|
const typebox_1 = require("@sinclair/typebox");
|
|
7
7
|
const common_1 = require("@appweaver/common");
|
|
8
8
|
const internal_1 = require("@appweaver/core/internal");
|
|
9
9
|
const core_1 = require("@appweaver/core");
|
|
10
|
+
const geo_schema_1 = require("../../spatial/geo-schema");
|
|
10
11
|
/** The schema name the shared field condition object is registered under. */
|
|
11
12
|
exports.QUERY_CONDITION_SCHEMA_NAME = 'QueryCondition';
|
|
13
|
+
/** The schema name the shared geo field condition object is registered under. */
|
|
14
|
+
exports.GEO_CONDITION_SCHEMA_NAME = 'GeoCondition';
|
|
12
15
|
/**
|
|
13
16
|
* Resolves the schema name the query filter of a model is registered under.
|
|
14
17
|
*
|
|
@@ -61,6 +64,33 @@ exports.QueryConditionSchema = typebox_1.Type.Object({
|
|
|
61
64
|
}, {
|
|
62
65
|
description: 'Field condition object combining comparison operators on a single field'
|
|
63
66
|
});
|
|
67
|
+
/**
|
|
68
|
+
* The shared schema of a geo field condition object, holding the spatial
|
|
69
|
+
* operators. Operators combined inside the same object must all match, and
|
|
70
|
+
* the distances are in meters.
|
|
71
|
+
*/
|
|
72
|
+
exports.GeoConditionSchema = typebox_1.Type.Object({
|
|
73
|
+
_near: Operator(typebox_1.Type.Object({
|
|
74
|
+
point: typebox_1.Type.Union([
|
|
75
|
+
(0, geo_schema_1.GeoPositionSchema)(),
|
|
76
|
+
(0, geo_schema_1.GeoLatLngSchema)(),
|
|
77
|
+
(0, geo_schema_1.geometrySchema)('Point')
|
|
78
|
+
]),
|
|
79
|
+
maxDistance: typebox_1.Type.Number({ minimum: 0 }),
|
|
80
|
+
minDistance: typebox_1.Type.Optional(typebox_1.Type.Number({ minimum: 0 }))
|
|
81
|
+
}), 'Matches geometries within maxDistance meters of the point (and at least minDistance away)'),
|
|
82
|
+
_within: Operator(typebox_1.Type.Union([(0, geo_schema_1.geometrySchema)('Polygon'), (0, geo_schema_1.geometrySchema)('MultiPolygon')]), 'Matches geometries covered by the GeoJSON polygon or multi polygon'),
|
|
83
|
+
_withinBox: Operator(typebox_1.Type.Tuple([
|
|
84
|
+
typebox_1.Type.Number({ minimum: -180, maximum: 180 }),
|
|
85
|
+
typebox_1.Type.Number({ minimum: -90, maximum: 90 }),
|
|
86
|
+
typebox_1.Type.Number({ minimum: -180, maximum: 180 }),
|
|
87
|
+
typebox_1.Type.Number({ minimum: -90, maximum: 90 })
|
|
88
|
+
]), 'Matches geometries covered by the box [minLng, minLat, maxLng, maxLat]'),
|
|
89
|
+
_intersects: Operator(typebox_1.Type.Union(common_1.GEO_FIELD_GEOMETRIES.geometry.map(geo_schema_1.geometrySchema)), 'Matches geometries sharing at least a point with the GeoJSON geometry'),
|
|
90
|
+
_exists: Operator(typebox_1.Type.Boolean(), 'Matches records with a geometry (true) or without one (false)')
|
|
91
|
+
}, {
|
|
92
|
+
description: 'Geo field condition object combining spatial operators on a single geo field'
|
|
93
|
+
});
|
|
64
94
|
/**
|
|
65
95
|
* Builds the query filter schema of a resource model, mirroring the WHERE part
|
|
66
96
|
* of a database query. Every filterable field of the model is declared
|
|
@@ -112,6 +142,14 @@ function buildQueryFilterSchema(model) {
|
|
|
112
142
|
? typebox_1.Type.Optional(typebox_1.Type.Any({ description: `Filter by the ${fieldName} field` }))
|
|
113
143
|
: scalarValue(`Filter by the ${fieldName} field`);
|
|
114
144
|
}
|
|
145
|
+
for (const [fieldName, geo] of Object.entries(model.config.geo ?? {})) {
|
|
146
|
+
if (geo.hidden) {
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
properties[fieldName] = typebox_1.Type.Optional(typebox_1.Type.Union([typebox_1.Type.Null(), typebox_1.Type.Ref(exports.GEO_CONDITION_SCHEMA_NAME)], {
|
|
150
|
+
description: `Filter by the ${fieldName} geo field with the spatial operators, or null for no value`
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
115
153
|
for (const [fieldName, relation] of Object.entries(model.config.relations ?? {})) {
|
|
116
154
|
properties[fieldName] = relationValue((0, exports.queryFilterName)((0, common_1.capitalize)(relation.model)), `Filter by the ${fieldName} relation, matching an id, a list of ids, ` +
|
|
117
155
|
`or a nested ${(0, common_1.capitalize)(relation.model)} filter`);
|
|
@@ -145,6 +183,7 @@ function registerQueryFilterSchemas() {
|
|
|
145
183
|
(0, core_1.createSchemaModel)(exports.QueryConditionSchema, {
|
|
146
184
|
name: exports.QUERY_CONDITION_SCHEMA_NAME
|
|
147
185
|
});
|
|
186
|
+
(0, core_1.createSchemaModel)(exports.GeoConditionSchema, { name: exports.GEO_CONDITION_SCHEMA_NAME });
|
|
148
187
|
for (const model of internal_1.context.resource.models.values()) {
|
|
149
188
|
(0, core_1.createSchemaModel)(buildQueryFilterSchema(model), {
|
|
150
189
|
name: (0, exports.queryFilterName)(model.name)
|
|
@@ -54,6 +54,16 @@ function buildQuerySortSchema(model) {
|
|
|
54
54
|
}
|
|
55
55
|
properties[fieldName] = SortDirection();
|
|
56
56
|
}
|
|
57
|
+
// A geo field is ordered by its distance from the point of its `_near`
|
|
58
|
+
// filter, and by nothing else
|
|
59
|
+
for (const [fieldName, geo] of Object.entries(model.config.geo ?? {})) {
|
|
60
|
+
if (geo.hidden) {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
properties[fieldName] = typebox_1.Type.Optional((0, common_1.StringEnum)(SORT_DIRECTIONS, {
|
|
64
|
+
description: `Sorts by the distance of ${fieldName} from the point of its _near filter, alone`
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
57
67
|
// A relation holding a list of records is ordered by their count, under the
|
|
58
68
|
// relation name and under its count field name alike
|
|
59
69
|
for (const [fieldName, relation] of Object.entries(model.config.relations ?? {})) {
|
|
@@ -7,6 +7,19 @@ export type DecodedCursor = {
|
|
|
7
7
|
/** True when the cursor pages towards the preceding records */
|
|
8
8
|
backward: boolean;
|
|
9
9
|
};
|
|
10
|
+
/**
|
|
11
|
+
* The key of the value a query condition is fingerprinted as instead of itself, i.e. the spatial filter a list of
|
|
12
|
+
* matching ids was resolved from, so a cursor stays valid while the records it matches change.
|
|
13
|
+
*/
|
|
14
|
+
export declare const FINGERPRINT: unique symbol;
|
|
15
|
+
/**
|
|
16
|
+
* Fingerprints a value as another one, see {@link FINGERPRINT}.
|
|
17
|
+
*
|
|
18
|
+
* @param {T} value - The value, an object or a list.
|
|
19
|
+
* @param {unknown} as - The value fingerprinted in its place.
|
|
20
|
+
* @return {T} The value.
|
|
21
|
+
*/
|
|
22
|
+
export declare function fingerprintAs<T extends object>(value: T, as: unknown): T;
|
|
10
23
|
/**
|
|
11
24
|
* Builds the fingerprint identifying the query a cursor belongs to. A cursor
|
|
12
25
|
* only yields the intended records while the resource, the query, and the order
|
|
@@ -1,10 +1,28 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FINGERPRINT = void 0;
|
|
4
|
+
exports.fingerprintAs = fingerprintAs;
|
|
3
5
|
exports.queryFingerprint = queryFingerprint;
|
|
4
6
|
exports.encodeCursor = encodeCursor;
|
|
5
7
|
exports.pageCursors = pageCursors;
|
|
6
8
|
exports.decodeCursor = decodeCursor;
|
|
7
9
|
const common_1 = require("@appweaver/common");
|
|
10
|
+
/**
|
|
11
|
+
* The key of the value a query condition is fingerprinted as instead of itself, i.e. the spatial filter a list of
|
|
12
|
+
* matching ids was resolved from, so a cursor stays valid while the records it matches change.
|
|
13
|
+
*/
|
|
14
|
+
exports.FINGERPRINT = Symbol('appweaver.fingerprint');
|
|
15
|
+
/**
|
|
16
|
+
* Fingerprints a value as another one, see {@link FINGERPRINT}.
|
|
17
|
+
*
|
|
18
|
+
* @param {T} value - The value, an object or a list.
|
|
19
|
+
* @param {unknown} as - The value fingerprinted in its place.
|
|
20
|
+
* @return {T} The value.
|
|
21
|
+
*/
|
|
22
|
+
function fingerprintAs(value, as) {
|
|
23
|
+
Object.defineProperty(value, exports.FINGERPRINT, { value: as, enumerable: false });
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
8
26
|
/**
|
|
9
27
|
* Builds the fingerprint identifying the query a cursor belongs to. A cursor
|
|
10
28
|
* only yields the intended records while the resource, the query, and the order
|
|
@@ -103,6 +121,9 @@ function decodeCursor(cursor, fingerprint) {
|
|
|
103
121
|
* @return {string} The serialized value.
|
|
104
122
|
*/
|
|
105
123
|
function stableStringify(value) {
|
|
124
|
+
if (value?.[exports.FINGERPRINT] !== undefined) {
|
|
125
|
+
return stableStringify(value[exports.FINGERPRINT]);
|
|
126
|
+
}
|
|
106
127
|
if ((0, common_1.isArray)(value)) {
|
|
107
128
|
return `[${value.map(stableStringify).join(',')}]`;
|
|
108
129
|
}
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The database conditions a filter field was resolved into ahead of the
|
|
3
|
+
* mapping, i.e. the ids matching the spatial operators of a geo field, added
|
|
4
|
+
* to the conditions of the level of the filter holding the field.
|
|
5
|
+
*/
|
|
6
|
+
export declare class ResolvedFilterConditions {
|
|
7
|
+
readonly conditions: any[];
|
|
8
|
+
constructor(conditions: any[]);
|
|
9
|
+
}
|
|
1
10
|
/**
|
|
2
11
|
* Maps a request filter to a Prisma `where` clause based on the schema of the
|
|
3
12
|
* given resource model. The logical operators (`_and`, `_or`, `_not`, `_nor`)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ResolvedFilterConditions = void 0;
|
|
3
4
|
exports.mapQueryFilter = mapQueryFilter;
|
|
4
5
|
const common_1 = require("@appweaver/common");
|
|
5
6
|
const core_1 = require("@appweaver/core");
|
|
@@ -44,6 +45,18 @@ const likePattern = (pattern) => {
|
|
|
44
45
|
}
|
|
45
46
|
return { equals: value };
|
|
46
47
|
};
|
|
48
|
+
/**
|
|
49
|
+
* The database conditions a filter field was resolved into ahead of the
|
|
50
|
+
* mapping, i.e. the ids matching the spatial operators of a geo field, added
|
|
51
|
+
* to the conditions of the level of the filter holding the field.
|
|
52
|
+
*/
|
|
53
|
+
class ResolvedFilterConditions {
|
|
54
|
+
conditions;
|
|
55
|
+
constructor(conditions) {
|
|
56
|
+
this.conditions = conditions;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
exports.ResolvedFilterConditions = ResolvedFilterConditions;
|
|
47
60
|
/**
|
|
48
61
|
* Field comparison operators mapped to their database query conditions.
|
|
49
62
|
* Operators combined in the same object are merged into a single condition.
|
|
@@ -100,6 +113,10 @@ function mapQueryFilter(filter, resourceName) {
|
|
|
100
113
|
const filesModel = resourceModel?.filesModel;
|
|
101
114
|
for (const key in filter) {
|
|
102
115
|
const value = filter[key];
|
|
116
|
+
if (value instanceof ResolvedFilterConditions) {
|
|
117
|
+
queryFilter['AND'] = [...(queryFilter['AND'] ?? []), ...value.conditions];
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
103
120
|
// Logical operators combine their conditions, given either as a filter
|
|
104
121
|
// object whose entries become separate conditions or as a list of
|
|
105
122
|
// filters, with the matching database connective
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { ActionType, QuerySort } from '@appweaver/common';
|
|
2
|
+
/** A single sort entry, holding a dot notation field path and its direction. */
|
|
3
|
+
type SortEntry = [path: string, direction: 'asc' | 'desc'];
|
|
2
4
|
/**
|
|
3
5
|
* Maps a sort input to the ordered list of Prisma `orderBy` entries. The input is accepted either as a comma-separated
|
|
4
6
|
* field list, where a field prefixed with `-` is sorted in descending order, or as a (possibly nested) object of `asc`
|
|
@@ -29,3 +31,15 @@ export declare function mapSortValues(sort: QuerySort, resourceName: string, act
|
|
|
29
31
|
* @throws {ResourceError} `RESOURCE_INVALID_SORT` under the same conditions as {@link mapSortValues}.
|
|
30
32
|
*/
|
|
31
33
|
export declare function mapStableSortValues(sort: QuerySort, resourceName: string, action?: ActionType): any[];
|
|
34
|
+
/**
|
|
35
|
+
* Flattens a sort input into the list of its field paths and directions, keeping the order the fields were declared
|
|
36
|
+
* in. String inputs are split on commas, with a `-` or `+` prefix selecting the direction, and object inputs are
|
|
37
|
+
* walked recursively, joining the nested keys with a dot.
|
|
38
|
+
*
|
|
39
|
+
* @param {QuerySort} sort - The sort input to flatten.
|
|
40
|
+
* @param {string} [parentPath] - The dot notation path of the object the walk descended from.
|
|
41
|
+
* @return {SortEntry[]} The flattened sort entries, each holding a dot notation field path and its direction.
|
|
42
|
+
* @throws {ResourceError} `RESOURCE_INVALID_SORT` if a sort value is neither a direction nor a nested object of directions.
|
|
43
|
+
*/
|
|
44
|
+
export declare function sortEntries(sort: QuerySort, parentPath?: string): SortEntry[];
|
|
45
|
+
export {};
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.mapSortValues = mapSortValues;
|
|
4
4
|
exports.mapStableSortValues = mapStableSortValues;
|
|
5
|
+
exports.sortEntries = sortEntries;
|
|
5
6
|
const common_1 = require("@appweaver/common");
|
|
6
7
|
const core_1 = require("@appweaver/core");
|
|
7
8
|
const relation_util_1 = require("./relation-util");
|