@twin.org/entity-storage-service 0.0.2-next.9 → 0.0.3-next.1

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.
Files changed (31) hide show
  1. package/dist/es/entityStorageRoutes.js +227 -0
  2. package/dist/es/entityStorageRoutes.js.map +1 -0
  3. package/dist/es/entityStorageService.js +122 -0
  4. package/dist/es/entityStorageService.js.map +1 -0
  5. package/dist/es/index.js +9 -0
  6. package/dist/es/index.js.map +1 -0
  7. package/dist/es/models/IEntityStorageRoutesExamples.js +2 -0
  8. package/dist/es/models/IEntityStorageRoutesExamples.js.map +1 -0
  9. package/dist/es/models/IEntityStorageServiceConfig.js +4 -0
  10. package/dist/es/models/IEntityStorageServiceConfig.js.map +1 -0
  11. package/dist/es/models/IEntityStorageServiceConstructorOptions.js +2 -0
  12. package/dist/es/models/IEntityStorageServiceConstructorOptions.js.map +1 -0
  13. package/dist/es/restEntryPoints.js +15 -0
  14. package/dist/es/restEntryPoints.js.map +1 -0
  15. package/dist/types/entityStorageRoutes.d.ts +1 -1
  16. package/dist/types/entityStorageService.d.ts +13 -12
  17. package/dist/types/index.d.ts +6 -6
  18. package/dist/types/models/IEntityStorageServiceConfig.d.ts +5 -0
  19. package/dist/types/models/IEntityStorageServiceConstructorOptions.d.ts +2 -2
  20. package/docs/changelog.md +45 -0
  21. package/docs/open-api/spec.json +14 -279
  22. package/docs/reference/classes/EntityStorageService.md +24 -34
  23. package/docs/reference/index.md +1 -1
  24. package/docs/reference/interfaces/IEntityStorageServiceConfig.md +3 -0
  25. package/docs/reference/interfaces/IEntityStorageServiceConstructorOptions.md +1 -1
  26. package/locales/en.json +1 -1
  27. package/package.json +11 -9
  28. package/dist/cjs/index.cjs +0 -421
  29. package/dist/esm/index.mjs +0 -412
  30. package/dist/types/models/IEntityStorageConfig.d.ts +0 -10
  31. package/docs/reference/interfaces/IEntityStorageConfig.md +0 -17
@@ -1,412 +0,0 @@
1
- import { HttpParameterHelper } from '@twin.org/api-models';
2
- import { StringHelper, Guards, ComponentFactory, Coerce, ObjectHelper, Is, NotFoundError } from '@twin.org/core';
3
- import { HttpStatusCode } from '@twin.org/web';
4
- import { LogicalOperator, ComparisonOperator, SortDirection, EntitySchemaHelper } from '@twin.org/entity';
5
- import { EntityStorageConnectorFactory } from '@twin.org/entity-storage-models';
6
-
7
- // Copyright 2024 IOTA Stiftung.
8
- // SPDX-License-Identifier: Apache-2.0.
9
- /**
10
- * The source used when communicating about these routes.
11
- */
12
- const ROUTES_SOURCE = "entityStorageRoutes";
13
- /**
14
- * The tag to associate with the routes.
15
- */
16
- const tagsEntityStorage = [
17
- {
18
- name: "EntityStorage",
19
- description: "Endpoints which are modelled to access an entity storage contract."
20
- }
21
- ];
22
- /**
23
- * The REST routes for entity storage.
24
- * @param baseRouteName Prefix to prepend to the paths.
25
- * @param componentName The name of the component to use in the routes stored in the ComponentFactory.
26
- * @param options Additional options for the routes.
27
- * @param options.typeName Optional type name to use in the routes, defaults to Entity Storage.
28
- * @param options.tagName Optional name to use in OpenAPI spec for tag.
29
- * @param options.examples Optional examples to use in the routes.
30
- * @returns The generated routes.
31
- */
32
- function generateRestRoutesEntityStorage(baseRouteName, componentName, options) {
33
- const typeName = options?.typeName ?? "Entity Storage";
34
- const lowerName = typeName.toLowerCase();
35
- const camelTypeName = StringHelper.camelCase(typeName);
36
- const setRoute = {
37
- operationId: `${camelTypeName}Set`,
38
- summary: `Set an entry in ${lowerName}.`,
39
- tag: options?.tagName ?? tagsEntityStorage[0].name,
40
- method: "POST",
41
- path: `${baseRouteName}/`,
42
- handler: async (httpRequestContext, request) => entityStorageSet(httpRequestContext, componentName, request),
43
- requestType: {
44
- type: "IEntityStorageSetRequest",
45
- examples: options?.examples?.set?.requestExamples ?? [
46
- {
47
- id: `${camelTypeName}SetRequestExample`,
48
- request: {
49
- body: {
50
- id: "12345",
51
- name: "My Item"
52
- }
53
- }
54
- }
55
- ]
56
- },
57
- responseType: [
58
- {
59
- type: "INoContentResponse"
60
- }
61
- ]
62
- };
63
- const getRoute = {
64
- operationId: `${camelTypeName}Get`,
65
- summary: `Get an entry from ${lowerName}.`,
66
- tag: options?.tagName ?? tagsEntityStorage[0].name,
67
- method: "GET",
68
- path: `${baseRouteName}/:id`,
69
- handler: async (httpRequestContext, request) => entityStorageGet(httpRequestContext, componentName, request),
70
- requestType: {
71
- type: "IEntityStorageGetRequest",
72
- examples: options?.examples?.get?.requestExamples ?? [
73
- {
74
- id: `${camelTypeName}GetRequestExample`,
75
- request: {
76
- pathParams: {
77
- id: "12345"
78
- }
79
- }
80
- }
81
- ]
82
- },
83
- responseType: [
84
- {
85
- type: "IEntityStorageGetResponse",
86
- examples: options?.examples?.get?.responseExamples ?? [
87
- {
88
- id: `${camelTypeName}GetResponseExample`,
89
- response: {
90
- body: {
91
- id: "12345",
92
- name: "My Item"
93
- }
94
- }
95
- }
96
- ]
97
- },
98
- {
99
- type: "INotFoundResponse"
100
- }
101
- ]
102
- };
103
- const removeRoute = {
104
- operationId: `${camelTypeName}Remove`,
105
- summary: `Remove an entry from ${lowerName}.`,
106
- tag: options?.tagName ?? tagsEntityStorage[0].name,
107
- method: "DELETE",
108
- path: `${baseRouteName}/:id`,
109
- handler: async (httpRequestContext, request) => entityStorageRemove(httpRequestContext, componentName, request),
110
- requestType: {
111
- type: "IEntityStorageRemoveRequest",
112
- examples: options?.examples?.remove?.requestExamples ?? [
113
- {
114
- id: `${camelTypeName}RemoveRequestExample`,
115
- request: {
116
- pathParams: {
117
- id: "12345"
118
- }
119
- }
120
- }
121
- ]
122
- },
123
- responseType: [
124
- {
125
- type: "INoContentResponse"
126
- },
127
- {
128
- type: "INotFoundResponse"
129
- }
130
- ]
131
- };
132
- const listRoute = {
133
- operationId: `${camelTypeName}List`,
134
- summary: `Query entries from ${lowerName}.`,
135
- tag: options?.tagName ?? tagsEntityStorage[0].name,
136
- method: "GET",
137
- path: `${baseRouteName}/`,
138
- handler: async (httpRequestContext, request) => entityStorageList(httpRequestContext, componentName, request),
139
- requestType: {
140
- type: "IEntityStorageListRequest",
141
- examples: options?.examples?.list?.requestExamples ?? [
142
- {
143
- id: `${camelTypeName}ListRequestExample`,
144
- request: {}
145
- }
146
- ]
147
- },
148
- responseType: [
149
- {
150
- type: "IEntityStorageListResponse",
151
- examples: options?.examples?.list?.responseExamples ?? [
152
- {
153
- id: `${camelTypeName}ListResponseExample`,
154
- response: {
155
- body: {
156
- entities: [{ id: "12345", name: "My Item" }]
157
- }
158
- }
159
- }
160
- ]
161
- }
162
- ]
163
- };
164
- return [setRoute, getRoute, removeRoute, listRoute];
165
- }
166
- /**
167
- * Set the entry in entity storage.
168
- * @param httpRequestContext The request context for the API.
169
- * @param componentName The name of the component to use in the routes.
170
- * @param request The request.
171
- * @returns The response object with additional http response properties.
172
- */
173
- async function entityStorageSet(httpRequestContext, componentName, request) {
174
- Guards.object(ROUTES_SOURCE, "request", request);
175
- const component = ComponentFactory.get(componentName);
176
- await component.set(request.body, httpRequestContext.userIdentity);
177
- return {
178
- statusCode: HttpStatusCode.noContent
179
- };
180
- }
181
- /**
182
- * Get the entry from entity storage.
183
- * @param httpRequestContext The request context for the API.
184
- * @param componentName The name of the component to use in the routes.
185
- * @param request The request.
186
- * @returns The response object with additional http response properties.
187
- */
188
- async function entityStorageGet(httpRequestContext, componentName, request) {
189
- Guards.object(ROUTES_SOURCE, "request", request);
190
- Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
191
- Guards.stringValue(ROUTES_SOURCE, "request.pathParams.id", request.pathParams.id);
192
- const component = ComponentFactory.get(componentName);
193
- const item = await component.get(request.pathParams.id, request.query?.secondaryIndex, httpRequestContext.userIdentity);
194
- return {
195
- body: item
196
- };
197
- }
198
- /**
199
- * Remove the entry from entity storage.
200
- * @param httpRequestContext The request context for the API.
201
- * @param componentName The name of the component to use in the routes.
202
- * @param request The request.
203
- * @returns The response object with additional http response properties.
204
- */
205
- async function entityStorageRemove(httpRequestContext, componentName, request) {
206
- Guards.object(ROUTES_SOURCE, "request", request);
207
- Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
208
- Guards.stringValue(ROUTES_SOURCE, "request.pathParams.id", request.pathParams.id);
209
- const component = ComponentFactory.get(componentName);
210
- await component.remove(request.pathParams.id, httpRequestContext.userIdentity);
211
- return {
212
- statusCode: HttpStatusCode.noContent
213
- };
214
- }
215
- /**
216
- * Query the entries from entity storage.
217
- * @param httpRequestContext The request context for the API.
218
- * @param componentName The name of the component to use in the routes.
219
- * @param request The request.
220
- * @returns The response object with additional http response properties.
221
- */
222
- async function entityStorageList(httpRequestContext, componentName, request) {
223
- Guards.object(ROUTES_SOURCE, "request", request);
224
- const component = ComponentFactory.get(componentName);
225
- const result = await component.query(HttpParameterHelper.objectFromString(request.query?.conditions), request.query?.orderBy, request.query?.orderByDirection, HttpParameterHelper.objectFromString(request.query?.properties), request.query?.cursor, Coerce.number(request.query?.pageSize), httpRequestContext.userIdentity);
226
- return {
227
- body: result
228
- };
229
- }
230
-
231
- // Copyright 2024 IOTA Stiftung.
232
- // SPDX-License-Identifier: Apache-2.0.
233
- /**
234
- * Class for performing entity service operations.
235
- */
236
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
237
- class EntityStorageService {
238
- /**
239
- * Runtime name for the class.
240
- */
241
- CLASS_NAME = "EntityStorageService";
242
- /**
243
- * The entity storage for items.
244
- * @internal
245
- */
246
- _entityStorage;
247
- /**
248
- * Include the user identity when performing storage operations, this allow separation of data per user, default to false.
249
- * @internal
250
- */
251
- _partitionPerUser;
252
- /**
253
- * Create a new instance of EntityStorageService.
254
- * @param options The dependencies for the entity storage service.
255
- */
256
- constructor(options) {
257
- Guards.string(this.CLASS_NAME, "options.entityStorageType", options.entityStorageType);
258
- this._entityStorage = EntityStorageConnectorFactory.get(options.entityStorageType);
259
- this._partitionPerUser = options.config?.partitionPerUser ?? false;
260
- }
261
- /**
262
- * Set an entity.
263
- * @param entity The entity to set.
264
- * @param userIdentity The user identity to use with storage operations.
265
- * @returns The id of the entity.
266
- */
267
- async set(entity, userIdentity) {
268
- Guards.object(this.CLASS_NAME, "entity", entity);
269
- const conditions = [];
270
- if (this._partitionPerUser) {
271
- Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
272
- conditions.push({
273
- property: "userIdentity",
274
- value: userIdentity
275
- });
276
- ObjectHelper.propertySet(entity, "userIdentity", userIdentity);
277
- }
278
- return this._entityStorage.set(entity, conditions);
279
- }
280
- /**
281
- * Get an entity.
282
- * @param id The id of the entity to get, or the index value if secondaryIndex is set.
283
- * @param secondaryIndex Get the item using a secondary index.
284
- * @param userIdentity The user identity to use with storage operations.
285
- * @returns The object if it can be found or undefined.
286
- */
287
- async get(id, secondaryIndex, userIdentity) {
288
- Guards.stringValue(this.CLASS_NAME, "id", id);
289
- return this.internalGet(id, secondaryIndex, userIdentity);
290
- }
291
- /**
292
- * Remove the entity.
293
- * @param id The id of the entity to remove.
294
- * @param userIdentity The user identity to use with storage operations.
295
- * @returns Nothing.
296
- */
297
- async remove(id, userIdentity) {
298
- Guards.stringValue(this.CLASS_NAME, "id", id);
299
- const conditions = [];
300
- if (this._partitionPerUser) {
301
- Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
302
- conditions.push({
303
- property: "userIdentity",
304
- value: userIdentity
305
- });
306
- }
307
- await this._entityStorage.remove(id, conditions);
308
- }
309
- /**
310
- * Query all the entities which match the conditions.
311
- * @param conditions The conditions to match for the entities.
312
- * @param orderBy The order for the results.
313
- * @param orderByDirection The direction for the order, defaults to ascending.
314
- * @param properties The optional properties to return, defaults to all.
315
- * @param cursor The cursor to request the next page of entities.
316
- * @param pageSize The suggested number of entities to return in each chunk, in some scenarios can return a different amount.
317
- * @param userIdentity The user identity to use with storage operations.
318
- * @returns All the entities for the storage matching the conditions,
319
- * and a cursor which can be used to request more entities.
320
- */
321
- async query(conditions, orderBy, orderByDirection, properties, cursor, pageSize, userIdentity) {
322
- const finalConditions = {
323
- conditions: [],
324
- logicalOperator: LogicalOperator.And
325
- };
326
- if (this._partitionPerUser) {
327
- Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
328
- finalConditions.conditions.push({
329
- property: "userIdentity",
330
- comparison: ComparisonOperator.Equals,
331
- value: userIdentity
332
- });
333
- }
334
- if (!Is.empty(conditions)) {
335
- finalConditions.conditions.push(conditions);
336
- }
337
- const result = await this._entityStorage.query(finalConditions.conditions.length > 0 ? finalConditions : undefined, Is.stringValue(orderBy)
338
- ? [{ property: orderBy, sortDirection: orderByDirection ?? SortDirection.Ascending }]
339
- : undefined, properties, cursor, pageSize);
340
- for (const entity of result.entities) {
341
- ObjectHelper.propertyDelete(entity, "userIdentity");
342
- }
343
- return result;
344
- }
345
- /**
346
- * Get an entity.
347
- * @param id The id of the entity to get, or the index value if secondaryIndex is set.
348
- * @param secondaryIndex Get the item using a secondary index.
349
- * @param userIdentity The user identity to use with storage operations.
350
- * @returns The object if it can be found or throws.
351
- * @internal
352
- */
353
- async internalGet(id, secondaryIndex, userIdentity) {
354
- const conditions = [];
355
- if (this._partitionPerUser) {
356
- Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
357
- conditions.push({
358
- property: "userIdentity",
359
- comparison: ComparisonOperator.Equals,
360
- value: userIdentity
361
- });
362
- }
363
- if (Is.stringValue(secondaryIndex)) {
364
- conditions.push({
365
- property: secondaryIndex,
366
- comparison: ComparisonOperator.Equals,
367
- value: id
368
- });
369
- }
370
- let entity;
371
- if (conditions.length === 0) {
372
- entity = await this._entityStorage.get(id, secondaryIndex);
373
- }
374
- else {
375
- if (!Is.stringValue(secondaryIndex)) {
376
- const schema = this._entityStorage.getSchema();
377
- const primaryKey = EntitySchemaHelper.getPrimaryKey(schema);
378
- conditions.unshift({
379
- property: primaryKey.property,
380
- comparison: ComparisonOperator.Equals,
381
- value: id
382
- });
383
- }
384
- const results = await this._entityStorage.query({
385
- conditions,
386
- logicalOperator: LogicalOperator.And
387
- }, undefined, undefined, undefined, 1);
388
- entity = results.entities[0];
389
- }
390
- if (Is.empty(entity)) {
391
- throw new NotFoundError(this.CLASS_NAME, "entityNotFound", id);
392
- }
393
- ObjectHelper.propertyDelete(entity, "userIdentity");
394
- return entity;
395
- }
396
- }
397
-
398
- /**
399
- * These are dummy entry points for the entity storage service.
400
- * In reality your application would create its own entry points based on the
401
- * entity storage schema objects it wants to store, using a custom defaultBaseRoute.
402
- */
403
- const restEntryPoints = [
404
- {
405
- name: "entity-storage",
406
- defaultBaseRoute: "entity-storage",
407
- tags: tagsEntityStorage,
408
- generateRoutes: generateRestRoutesEntityStorage
409
- }
410
- ];
411
-
412
- export { EntityStorageService, entityStorageGet, entityStorageList, entityStorageRemove, entityStorageSet, generateRestRoutesEntityStorage, restEntryPoints, tagsEntityStorage };
@@ -1,10 +0,0 @@
1
- /**
2
- * Configuration for the entity storage service.
3
- */
4
- export interface IEntityStorageConfig {
5
- /**
6
- * Include the user identity when performing storage operations, this allow separation of data per user.
7
- * @default false
8
- */
9
- partitionPerUser?: boolean;
10
- }
@@ -1,17 +0,0 @@
1
- # Interface: IEntityStorageConfig
2
-
3
- Configuration for the entity storage service.
4
-
5
- ## Properties
6
-
7
- ### partitionPerUser?
8
-
9
- > `optional` **partitionPerUser**: `boolean`
10
-
11
- Include the user identity when performing storage operations, this allow separation of data per user.
12
-
13
- #### Default
14
-
15
- ```ts
16
- false
17
- ```