@opra/sqb 0.33.13 → 1.0.0-alpha.2

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 (43) hide show
  1. package/cjs/{transform-filter.js → adapter-utils/parse-filter.js} +37 -12
  2. package/cjs/augmentation/datatype-factory.augmentation.js +75 -0
  3. package/cjs/augmentation/mixin-type.augmentation.js +5 -3
  4. package/cjs/index.js +3 -4
  5. package/cjs/sqb-adapter.js +66 -100
  6. package/cjs/sqb-collection-service.js +297 -0
  7. package/cjs/sqb-entity-service.js +444 -25
  8. package/cjs/sqb-singleton-service.js +180 -0
  9. package/esm/{transform-filter.js → adapter-utils/parse-filter.js} +36 -11
  10. package/esm/augmentation/datatype-factory.augmentation.js +73 -0
  11. package/esm/augmentation/mapped-type.augmentation.js +1 -1
  12. package/esm/augmentation/mixin-type.augmentation.js +6 -4
  13. package/esm/index.js +3 -4
  14. package/esm/sqb-adapter.js +66 -100
  15. package/esm/sqb-collection-service.js +293 -0
  16. package/esm/sqb-entity-service.js +444 -25
  17. package/esm/sqb-singleton-service.js +176 -0
  18. package/package.json +10 -9
  19. package/types/adapter-utils/parse-filter.d.ts +10 -0
  20. package/types/index.d.ts +3 -4
  21. package/types/sqb-adapter.d.ts +10 -8
  22. package/types/sqb-collection-service.d.ts +233 -0
  23. package/types/sqb-entity-service.d.ts +418 -18
  24. package/types/sqb-singleton-service.d.ts +137 -0
  25. package/cjs/augmentation/api-document-factory.augmentation.js +0 -20
  26. package/cjs/augmentation/type-document-factory.augmentation.js +0 -99
  27. package/cjs/sqb-collection.js +0 -80
  28. package/cjs/sqb-entity-service-base.js +0 -170
  29. package/cjs/sqb-singleton.js +0 -44
  30. package/cjs/transform-key-values.js +0 -14
  31. package/esm/augmentation/api-document-factory.augmentation.js +0 -18
  32. package/esm/augmentation/type-document-factory.augmentation.js +0 -97
  33. package/esm/sqb-collection.js +0 -76
  34. package/esm/sqb-entity-service-base.js +0 -166
  35. package/esm/sqb-singleton.js +0 -40
  36. package/esm/transform-key-values.js +0 -11
  37. package/types/augmentation/type-document-factory.augmentation.d.ts +0 -1
  38. package/types/sqb-collection.d.ts +0 -31
  39. package/types/sqb-entity-service-base.d.ts +0 -31
  40. package/types/sqb-singleton.d.ts +0 -18
  41. package/types/transform-filter.d.ts +0 -3
  42. package/types/transform-key-values.d.ts +0 -3
  43. /package/types/augmentation/{api-document-factory.augmentation.d.ts → datatype-factory.augmentation.d.ts} +0 -0
@@ -1,13 +1,38 @@
1
1
  import '@opra/core';
2
2
  import { OpraFilter } from '@opra/common';
3
3
  import * as sqb from '@sqb/builder';
4
- export default function transformFilter(ast) {
4
+ /**
5
+ * Prepare the SQB filter based on the provided filters and options.
6
+ *
7
+ * @param {SQBAdapter.FilterInput|SQBAdapter.FilterInput[]} filters - The filter(s) to be applied.
8
+ *
9
+ * @returns {Expression} - The prepared SQB Expression.
10
+ */
11
+ export default function parseFilter(filters) {
12
+ const filtersArray = Array.isArray(filters) ? filters : [filters];
13
+ if (!filtersArray.length)
14
+ return undefined;
15
+ const arr = [];
16
+ for (const filter of filtersArray) {
17
+ if (!filter)
18
+ continue;
19
+ let ast;
20
+ if (typeof filter === 'string')
21
+ ast = prepareFilterAst(OpraFilter.parse(filter));
22
+ else if (filter instanceof OpraFilter.Expression)
23
+ ast = prepareFilterAst(filter);
24
+ else
25
+ ast = filter;
26
+ if (ast)
27
+ arr.push(ast);
28
+ }
29
+ return arr.length > 1 ? sqb.And(...arr) : arr[0];
30
+ }
31
+ function prepareFilterAst(ast) {
5
32
  if (!ast)
6
33
  return;
7
- if (ast instanceof OpraFilter.QualifiedIdentifier) {
8
- return sqb.Field(ast.value);
9
- }
10
- if (ast instanceof OpraFilter.NumberLiteral ||
34
+ if (ast instanceof OpraFilter.QualifiedIdentifier ||
35
+ ast instanceof OpraFilter.NumberLiteral ||
11
36
  ast instanceof OpraFilter.StringLiteral ||
12
37
  ast instanceof OpraFilter.BooleanLiteral ||
13
38
  ast instanceof OpraFilter.NullLiteral ||
@@ -16,22 +41,22 @@ export default function transformFilter(ast) {
16
41
  return ast.value;
17
42
  }
18
43
  if (ast instanceof OpraFilter.ArrayExpression) {
19
- return ast.items.map(transformFilter);
44
+ return ast.items.map(prepareFilterAst);
20
45
  }
21
46
  if (ast instanceof OpraFilter.NegativeExpression) {
22
- return sqb.Not(transformFilter(ast.expression));
47
+ return sqb.Not(prepareFilterAst(ast.expression));
23
48
  }
24
49
  if (ast instanceof OpraFilter.LogicalExpression) {
25
50
  if (ast.op === 'or')
26
- return sqb.Or(...ast.items.map(transformFilter));
27
- return sqb.And(...ast.items.map(transformFilter));
51
+ return sqb.Or(...ast.items.map(prepareFilterAst));
52
+ return sqb.And(...ast.items.map(prepareFilterAst));
28
53
  }
29
54
  if (ast instanceof OpraFilter.ParenthesizedExpression) {
30
- return transformFilter(ast.expression);
55
+ return prepareFilterAst(ast.expression);
31
56
  }
32
57
  if (ast instanceof OpraFilter.ComparisonExpression) {
33
58
  const left = String(ast.left);
34
- const right = transformFilter(ast.right);
59
+ const right = prepareFilterAst(ast.right);
35
60
  switch (ast.op) {
36
61
  case '=':
37
62
  return sqb.Eq(left, right);
@@ -0,0 +1,73 @@
1
+ import { classes, cloneObject } from '@opra/common';
2
+ import { DataType as SqbDataType, EntityMetadata, isAssociationField, isColumnField } from '@sqb/connect';
3
+ var DataTypeFactory = classes.DataTypeFactory;
4
+ const _prepareComplexTypeArgs = DataTypeFactory._prepareComplexTypeArgs;
5
+ DataTypeFactory._prepareComplexTypeArgs = async function (context, owner, initArgs, metadata) {
6
+ let sqbMeta;
7
+ if (initArgs.ctor && metadata.fields && (sqbMeta = EntityMetadata.get(initArgs.ctor))) {
8
+ metadata = cloneObject(metadata);
9
+ for (const [fieldName, fieldSchema] of Object.entries(metadata.fields)) {
10
+ const sqbField = sqbMeta && EntityMetadata.getField(sqbMeta, fieldName);
11
+ if (!sqbField)
12
+ continue;
13
+ /** Copy type information from sqb metadata to opra */
14
+ if (!fieldSchema.type || fieldSchema.type === Object) {
15
+ if (isAssociationField(sqbField)) {
16
+ if (!fieldSchema.type) {
17
+ const trg = await sqbField.association.resolveTarget();
18
+ if (trg?.ctor)
19
+ fieldSchema.type = trg.ctor;
20
+ }
21
+ }
22
+ else if (isColumnField(sqbField)) {
23
+ fieldSchema.type = sqbField.enum || sqbField.type;
24
+ }
25
+ }
26
+ if (isColumnField(sqbField)) {
27
+ const hasNoType = !fieldSchema.type || fieldSchema.type === Object;
28
+ switch (sqbField.dataType) {
29
+ case SqbDataType.INTEGER:
30
+ case SqbDataType.SMALLINT:
31
+ if (hasNoType || fieldSchema.type === Number)
32
+ fieldSchema.type = 'integer';
33
+ break;
34
+ case SqbDataType.GUID:
35
+ if (hasNoType || fieldSchema.type === String)
36
+ fieldSchema.type = 'uuid';
37
+ break;
38
+ case SqbDataType.DATE:
39
+ if (fieldSchema.type === String)
40
+ fieldSchema.type = 'datestring';
41
+ else if (hasNoType || fieldSchema.type === Date)
42
+ fieldSchema.type = 'date';
43
+ break;
44
+ case SqbDataType.TIMESTAMP:
45
+ if (fieldSchema.type === String)
46
+ fieldSchema.type = 'datetimestring';
47
+ else if (hasNoType || fieldSchema.type === Date)
48
+ fieldSchema.type = 'datetime';
49
+ break;
50
+ case SqbDataType.TIMESTAMPTZ:
51
+ if (fieldSchema.type === Date)
52
+ fieldSchema.type = 'datetime';
53
+ else if (hasNoType || fieldSchema.type === String)
54
+ fieldSchema.type = 'datetimestring';
55
+ break;
56
+ case SqbDataType.TIME:
57
+ if (hasNoType || fieldSchema.type === String)
58
+ fieldSchema.type = 'time';
59
+ break;
60
+ }
61
+ }
62
+ if (isAssociationField(sqbField)) {
63
+ if (sqbField.association.returnsMany())
64
+ fieldSchema.isArray = true;
65
+ if (!fieldSchema.hasOwnProperty('exclusive'))
66
+ fieldSchema.exclusive = true;
67
+ }
68
+ if (!fieldSchema.hasOwnProperty('exclusive') && sqbField.hasOwnProperty('exclusive'))
69
+ fieldSchema.exclusive = sqbField.exclusive;
70
+ }
71
+ }
72
+ return _prepareComplexTypeArgs.apply(DataTypeFactory, [context, owner, initArgs, metadata]);
73
+ };
@@ -1,4 +1,4 @@
1
- import { MappedType } from "@opra/common";
1
+ import { MappedType } from '@opra/common';
2
2
  import { Entity, EntityMetadata } from '@sqb/connect';
3
3
  const _applyMixin = MappedType._applyMixin;
4
4
  MappedType._applyMixin = function (targetType, sourceType, options) {
@@ -1,7 +1,9 @@
1
- import { MixinType } from "@opra/common";
1
+ import { DECORATOR, MixinType } from '@opra/common';
2
2
  import { Entity } from '@sqb/connect';
3
- const _applyMixin = MixinType._applyMixin;
4
- MixinType._applyMixin = function (target, ...sources) {
5
- _applyMixin.call(null, target, ...sources);
3
+ const oldDecorator = MixinType[DECORATOR];
4
+ MixinType[DECORATOR] = function (...sources) {
5
+ sources = sources.filter(x => typeof x === 'function');
6
+ const target = oldDecorator(...sources);
6
7
  Entity.mixin(target, ...sources);
8
+ return target;
7
9
  };
package/esm/index.js CHANGED
@@ -1,8 +1,7 @@
1
- import './augmentation/type-document-factory.augmentation.js';
2
- import './augmentation/api-document-factory.augmentation.js';
1
+ import './augmentation/datatype-factory.augmentation.js';
3
2
  import './augmentation/mapped-type.augmentation.js';
4
3
  import './augmentation/mixin-type.augmentation.js';
5
4
  export * from './sqb-adapter.js';
6
- export * from './sqb-collection.js';
5
+ export * from './sqb-collection-service.js';
7
6
  export * from './sqb-entity-service.js';
8
- export * from './sqb-singleton.js';
7
+ export * from './sqb-singleton-service.js';
@@ -1,109 +1,75 @@
1
- import { Collection, omitNullish, Singleton } from '@opra/common';
2
1
  import { EntityMetadata } from '@sqb/connect';
3
- import _transformFilter from './transform-filter.js';
4
- import _transformKeyValues from './transform-key-values.js';
2
+ import _parseFilter from './adapter-utils/parse-filter.js';
5
3
  export var SQBAdapter;
6
4
  (function (SQBAdapter) {
7
- SQBAdapter.transformFilter = _transformFilter;
8
- SQBAdapter.transformKeyValues = _transformKeyValues;
9
- function transformRequest(request) {
10
- const { resource } = request;
11
- if (resource instanceof Collection || resource instanceof Singleton) {
12
- const { params, endpoint } = request;
13
- let options = {};
14
- const entityMetadata = EntityMetadata.get(resource.type.ctor);
5
+ SQBAdapter.parseFilter = _parseFilter;
6
+ async function parseRequest(context) {
7
+ const { operation } = context;
8
+ if (operation.composition?.startsWith('Entity.') && operation.compositionOptions?.type) {
9
+ const dataType = context.document.node.getComplexType(operation.compositionOptions?.type);
10
+ const entityMetadata = EntityMetadata.get(dataType.ctor);
15
11
  if (!entityMetadata)
16
- throw new Error(`Type class "${resource.type.ctor}" is not an SQB entity`);
17
- if (resource instanceof Collection) {
18
- const primaryIndex = entityMetadata.indexes.find(x => x.primary);
19
- // Check if resource primary keys are same with entity
20
- const primaryKeys = [...(primaryIndex && primaryIndex.columns) || []];
21
- if (primaryKeys.sort().join() !== [...resource.primaryKey].sort().join())
22
- throw new Error('Resource primaryKey definition differs from SQB Entity primaryKey definition');
23
- }
24
- const operation = endpoint.name;
25
- if (operation === 'create' || operation === 'update' ||
26
- operation === 'get' || operation === 'findMany') {
27
- options.pick = params?.pick;
28
- options.omit = params?.omit;
29
- options.include = params?.include;
30
- }
31
- if (resource instanceof Collection && params?.filter) {
32
- options.filter = _transformFilter(params.filter);
33
- }
34
- if (operation === 'findMany') {
35
- options.sort = params?.sort;
36
- options.limit = params?.limit;
37
- options.offset = params?.skip;
38
- options.distinct = params?.distinct;
39
- options.count = params?.count;
40
- }
41
- options = omitNullish(options);
42
- if (operation === 'create') {
43
- return {
44
- method: 'create',
45
- data: request.data,
46
- options,
47
- args: [request.data, options]
48
- };
49
- }
50
- if (operation === 'deleteMany' || (operation === 'delete' && resource instanceof Singleton)) {
51
- return {
52
- method: 'deleteMany',
53
- options,
54
- args: [options]
55
- };
56
- }
57
- if (operation === 'delete') {
58
- return {
59
- method: 'delete',
60
- key: request.key,
61
- options,
62
- args: [request.key, options]
63
- };
64
- }
65
- if (operation === 'get') {
66
- if (resource instanceof Singleton)
67
- return {
68
- method: 'findOne',
69
- options,
70
- args: [options]
12
+ throw new Error(`Type class "${dataType.ctor}" is not an SQB entity`);
13
+ const { compositionOptions } = operation;
14
+ switch (operation.composition) {
15
+ case 'Entity.Create': {
16
+ const data = await context.getBody();
17
+ const options = {
18
+ projection: context.queryParams.projection,
71
19
  };
72
- return {
73
- method: 'find',
74
- key: request.key,
75
- options,
76
- args: [request.key, options]
77
- };
78
- }
79
- if (operation === 'findMany') {
80
- const out = {
81
- method: 'findMany',
82
- options,
83
- args: [options]
84
- };
85
- out.count = params?.count;
86
- return out;
87
- }
88
- if (operation === 'updateMany' || (operation === 'update' && resource instanceof Singleton)) {
89
- return {
90
- method: 'updateMany',
91
- data: request.data,
92
- options,
93
- args: [request.data, options]
94
- };
95
- }
96
- if (operation === 'update') {
97
- return {
98
- method: 'update',
99
- key: request.key,
100
- data: request.data,
101
- options,
102
- args: [request.key, request.data, options]
103
- };
20
+ return { method: 'create', data, options };
21
+ }
22
+ case 'Entity.Delete': {
23
+ const key = context.pathParams[compositionOptions.keyParameter];
24
+ const options = {
25
+ filter: SQBAdapter.parseFilter(context.queryParams.filter),
26
+ };
27
+ return { method: 'delete', key, options };
28
+ }
29
+ case 'Entity.DeleteMany': {
30
+ const options = {
31
+ filter: SQBAdapter.parseFilter(context.queryParams.filter),
32
+ };
33
+ return { method: 'deleteMany', options };
34
+ }
35
+ case 'Entity.FindMany': {
36
+ const options = {
37
+ count: context.queryParams.count,
38
+ filter: SQBAdapter.parseFilter(context.queryParams.filter),
39
+ limit: context.queryParams.limit,
40
+ offset: context.queryParams.skip,
41
+ projection: context.queryParams.projection,
42
+ sort: context.queryParams.sort,
43
+ };
44
+ return { method: 'findMany', options };
45
+ }
46
+ case 'Entity.Get': {
47
+ const key = context.pathParams[compositionOptions.keyParameter];
48
+ const options = {
49
+ projection: context.queryParams.projection,
50
+ filter: SQBAdapter.parseFilter(context.queryParams.filter),
51
+ };
52
+ return { method: 'get', key, options };
53
+ }
54
+ case 'Entity.Update': {
55
+ const data = await context.getBody();
56
+ const key = context.pathParams[compositionOptions.keyParameter];
57
+ const options = {
58
+ projection: context.queryParams.projection,
59
+ filter: SQBAdapter.parseFilter(context.queryParams.filter),
60
+ };
61
+ return { method: 'update', key, data, options };
62
+ }
63
+ case 'Entity.UpdateMany': {
64
+ const data = await context.getBody();
65
+ const options = {
66
+ filter: SQBAdapter.parseFilter(context.queryParams.filter),
67
+ };
68
+ return { method: 'updateMany', data, options };
69
+ }
104
70
  }
105
71
  }
106
- throw new Error(`Unimplemented request method "${request.operation}"`);
72
+ throw new Error(`This operation is not compatible to SQB Adapter`);
107
73
  }
108
- SQBAdapter.transformRequest = transformRequest;
74
+ SQBAdapter.parseRequest = parseRequest;
109
75
  })(SQBAdapter || (SQBAdapter = {}));
@@ -0,0 +1,293 @@
1
+ import { ResourceNotAvailableError } from '@opra/common';
2
+ import { SQBAdapter } from './sqb-adapter.js';
3
+ import { SqbEntityService } from './sqb-entity-service.js';
4
+ /**
5
+ * @class SqbCollectionService
6
+ * @template T - The data type class type of the resource
7
+ */
8
+ export class SqbCollectionService extends SqbEntityService {
9
+ /**
10
+ * Constructs a new instance
11
+ *
12
+ * @param {Type | string} dataType - The data type of the array elements.
13
+ * @param {SqbCollectionService.Options} [options] - The options for the array service.
14
+ * @constructor
15
+ */
16
+ constructor(dataType, options) {
17
+ super(dataType, options);
18
+ this.defaultLimit = options?.defaultLimit || 100;
19
+ }
20
+ /**
21
+ * Asserts the existence of a resource with the given ID.
22
+ * Throws a ResourceNotFoundError if the resource does not exist.
23
+ *
24
+ * @param {SQBAdapter.IdOrIds} id - The ID of the resource to assert.
25
+ * @param {SqbCollectionService.ExistsOptions} [options] - Optional options for checking the existence.
26
+ * @returns {Promise<void>} - A Promise that resolves when the resource exists.
27
+ * @throws {ResourceNotAvailableError} - If the resource does not exist.
28
+ */
29
+ async assert(id, options) {
30
+ if (!(await this.exists(id, options)))
31
+ throw new ResourceNotAvailableError(this.getResourceName(), id);
32
+ }
33
+ /**
34
+ * Creates a new resource
35
+ *
36
+ * @param {PartialDTO<T>} input - The input data
37
+ * @param {SqbCollectionService.CreateOptions} [options] - The options object
38
+ * @returns {Promise<PartialDTO<T>>} A promise that resolves to the created resource
39
+ * @throws {Error} if an unknown error occurs while creating the resource
40
+ */
41
+ async create(input, options) {
42
+ const info = {
43
+ crud: 'create',
44
+ method: 'create',
45
+ byId: false,
46
+ input,
47
+ options,
48
+ };
49
+ return this._intercept(() => this._create(input, options), info);
50
+ }
51
+ /**
52
+ * Returns the count of records based on the provided options
53
+ *
54
+ * @param {SqbCollectionService.CountOptions} options - The options for the count operation.
55
+ * @return {Promise<number>} - A promise that resolves to the count of records
56
+ */
57
+ async count(options) {
58
+ const info = {
59
+ crud: 'read',
60
+ method: 'count',
61
+ byId: false,
62
+ options,
63
+ };
64
+ return this._intercept(async () => {
65
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
66
+ return this._count({ ...options, filter });
67
+ }, info);
68
+ }
69
+ /**
70
+ * Deletes a record from the collection.
71
+ *
72
+ * @param {SQBAdapter.IdOrIds} id - The ID of the document to delete.
73
+ * @param {SqbCollectionService.DeleteOptions} [options] - Optional delete options.
74
+ * @return {Promise<number>} - A Promise that resolves to the number of documents deleted.
75
+ */
76
+ async delete(id, options) {
77
+ const info = {
78
+ crud: 'delete',
79
+ method: 'delete',
80
+ byId: true,
81
+ documentId: id,
82
+ options,
83
+ };
84
+ return this._intercept(async () => {
85
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
86
+ return this._delete(id, { ...options, filter });
87
+ }, info);
88
+ }
89
+ /**
90
+ * Deletes multiple documents from the collection that meet the specified filter criteria.
91
+ *
92
+ * @param {SqbCollectionService.DeleteManyOptions} options - The options for the delete operation.
93
+ * @return {Promise<number>} - A promise that resolves to the number of documents deleted.
94
+ */
95
+ async deleteMany(options) {
96
+ const info = {
97
+ crud: 'delete',
98
+ method: 'deleteMany',
99
+ byId: false,
100
+ options,
101
+ };
102
+ return this._intercept(async () => {
103
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
104
+ return this._deleteMany({ ...options, filter });
105
+ }, info);
106
+ }
107
+ /**
108
+ * Checks if a record with the given id exists.
109
+ *
110
+ * @param {SQBAdapter.IdOrIds} id - The id of the object to check.
111
+ * @param {SqbCollectionService.ExistsOptions} [options] - The options for the query (optional).
112
+ * @return {Promise<boolean>} - A Promise that resolves to a boolean indicating whether the record exists or not.
113
+ */
114
+ async exists(id, options) {
115
+ const info = {
116
+ crud: 'read',
117
+ method: 'exists',
118
+ byId: true,
119
+ documentId: id,
120
+ options,
121
+ };
122
+ return this._intercept(async () => {
123
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
124
+ return this._exists(id, { ...options, filter });
125
+ }, info);
126
+ }
127
+ /**
128
+ * Checks if a record with the given arguments exists.
129
+ *
130
+ * @param {SqbCollectionService.ExistsOneOptions} [options] - The options for the query (optional).
131
+ * @return {Promise<boolean>} - A Promise that resolves to a boolean indicating whether the record exists or not.
132
+ */
133
+ async existsOne(options) {
134
+ const info = {
135
+ crud: 'read',
136
+ method: 'existsOne',
137
+ byId: false,
138
+ options,
139
+ };
140
+ return this._intercept(async () => {
141
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
142
+ return this._existsOne({ ...options, filter });
143
+ }, info);
144
+ }
145
+ /**
146
+ * Finds a record by ID.
147
+ *
148
+ * @param {SQBAdapter.Id} id - The ID of the record.
149
+ * @param {SqbCollectionService.FindOneOptions} [options] - The options for the find query.
150
+ * @return {Promise<PartialDTO<T | undefined>>} - A promise resolving to the found document, or undefined if not found.
151
+ */
152
+ async findById(id, options) {
153
+ const info = {
154
+ crud: 'read',
155
+ method: 'findById',
156
+ byId: true,
157
+ documentId: id,
158
+ options,
159
+ };
160
+ return this._intercept(async () => {
161
+ const documentFilter = await this._getCommonFilter(info);
162
+ const filter = SQBAdapter.parseFilter([documentFilter, options?.filter]);
163
+ return this._findById(id, { ...options, filter });
164
+ }, info);
165
+ }
166
+ /**
167
+ * Finds a record in the collection that matches the specified options.
168
+ *
169
+ * @param {SqbCollectionService.FindOneOptions} options - The options for the query.
170
+ * @return {Promise<PartialDTO<T> | undefined>} A promise that resolves with the found document or undefined if no document is found.
171
+ */
172
+ async findOne(options) {
173
+ const info = {
174
+ crud: 'read',
175
+ method: 'findOne',
176
+ byId: false,
177
+ options,
178
+ };
179
+ return this._intercept(async () => {
180
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
181
+ return this._findOne({ ...options, filter });
182
+ }, info);
183
+ }
184
+ /**
185
+ * Finds multiple records in collection.
186
+ *
187
+ * @param {SqbCollectionService.FindManyOptions} options - The options for the find operation.
188
+ * @return A Promise that resolves to an array of partial outputs of type T.
189
+ */
190
+ async findMany(options) {
191
+ const info = {
192
+ crud: 'read',
193
+ method: 'findMany',
194
+ byId: false,
195
+ options,
196
+ };
197
+ return this._intercept(async () => {
198
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
199
+ return this._findMany({ ...options, filter });
200
+ }, info);
201
+ }
202
+ /**
203
+ * Finds multiple records in the collection and returns both records (max limit)
204
+ * and total count that matched the given criteria
205
+ *
206
+ * @param {SqbCollectionService.FindManyOptions} options - The options for the find operation.
207
+ * @return A Promise that resolves to an array of partial outputs of type T and total count.
208
+ */
209
+ async findManyWithCount(options) {
210
+ const [items, count] = await Promise.all([this.findMany(options), this.count(options)]);
211
+ return { count, items };
212
+ }
213
+ /**
214
+ * Retrieves a records from the collection by its ID. Throws error if not found.
215
+ *
216
+ * @param {SQBAdapter.Id} id - The ID of the document to retrieve.
217
+ * @param {SqbCollectionService.FindOneOptions} [options] - Optional options for the findOne operation.
218
+ * @returns {Promise<PartialDTO<T>>} - A promise that resolves to the retrieved document,
219
+ * or rejects with a ResourceNotFoundError if the document does not exist.
220
+ * @throws {ResourceNotAvailableError} - If the document with the specified ID does not exist.
221
+ */
222
+ async get(id, options) {
223
+ const out = await this.findById(id, options);
224
+ if (!out)
225
+ throw new ResourceNotAvailableError(this.getResourceName(), id);
226
+ return out;
227
+ }
228
+ /**
229
+ * Updates a record with the given id in the collection.
230
+ *
231
+ * @param {SQBAdapter.IdOrIds} id - The id of the document to update.
232
+ * @param {PatchDTO<T>} input - The partial input object containing the fields to update.
233
+ * @param {SqbCollectionService.UpdateOptions} [options] - The options for the update operation.
234
+ * @returns {Promise<PartialDTO<T> | undefined>} A promise that resolves to the updated document or
235
+ * undefined if the document was not found.
236
+ */
237
+ async update(id, input, options) {
238
+ const info = {
239
+ crud: 'update',
240
+ method: 'update',
241
+ documentId: id,
242
+ byId: true,
243
+ input,
244
+ options,
245
+ };
246
+ return this._intercept(async () => {
247
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
248
+ return this._update(id, input, { ...options, filter });
249
+ }, info);
250
+ }
251
+ /**
252
+ * Updates a record in the collection with the specified ID and returns updated record count
253
+ *
254
+ * @param {any} id - The ID of the document to update.
255
+ * @param {PatchDTO<T>} input - The partial input data to update the document with.
256
+ * @param {SqbCollectionService.UpdateOptions} options - The options for updating the document.
257
+ * @returns {Promise<number>} - A promise that resolves to the number of documents modified.
258
+ */
259
+ async updateOnly(id, input, options) {
260
+ const info = {
261
+ crud: 'update',
262
+ method: 'update',
263
+ documentId: id,
264
+ byId: true,
265
+ input,
266
+ options,
267
+ };
268
+ return this._intercept(async () => {
269
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
270
+ return this._updateOnly(id, input, { ...options, filter });
271
+ }, info);
272
+ }
273
+ /**
274
+ * Updates multiple records in the collection based on the specified input and options.
275
+ *
276
+ * @param {PatchDTO<T>} input - The partial input to update the documents with.
277
+ * @param {SqbCollectionService.UpdateManyOptions} options - The options for updating the documents.
278
+ * @return {Promise<number>} - A promise that resolves to the number of documents matched and modified.
279
+ */
280
+ async updateMany(input, options) {
281
+ const info = {
282
+ crud: 'update',
283
+ method: 'updateMany',
284
+ byId: false,
285
+ input,
286
+ options,
287
+ };
288
+ return this._intercept(async () => {
289
+ const filter = SQBAdapter.parseFilter([await this._getCommonFilter(info), options?.filter]);
290
+ return this._updateMany(input, { ...options, filter });
291
+ }, info);
292
+ }
293
+ }