@venizia/ignis-kernel 0.4.8-9 → 0.4.8
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/dist/esm/base/applications/artifact-index.d.ts +3 -3
- package/dist/esm/base/applications/artifact-index.js.map +1 -1
- package/dist/esm/base/applications/body-limit.js +1 -1
- package/dist/esm/base/applications/body-limit.js.map +1 -1
- package/dist/esm/base/applications/common/types/application.d.ts +2 -2
- package/dist/esm/base/applications/common/types/application.js.map +1 -1
- package/dist/esm/base/applications/common/types/middlewares.d.ts +2 -2
- package/dist/esm/base/applications/common/types/middlewares.js.map +1 -1
- package/dist/esm/base/applications/rest.js +6 -1
- package/dist/esm/base/applications/rest.js.map +1 -1
- package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +1 -1
- package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
- package/dist/esm/base/auth/authenticate/common/types/strategy.d.ts +2 -3
- package/dist/esm/base/auth/authenticate/common/types/strategy.js.map +1 -1
- package/dist/esm/base/auth/authenticate/strategies/strategy-registry.d.ts +1 -1
- package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js +1 -1
- package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js.map +1 -1
- package/dist/esm/base/auth/authorize/providers/request-domain.js +2 -1
- package/dist/esm/base/auth/authorize/providers/request-domain.js.map +1 -1
- package/dist/esm/base/controllers/common/types/route.d.ts +13 -4
- package/dist/esm/base/controllers/common/types/route.js.map +1 -1
- package/dist/esm/base/controllers/factory/controller.d.ts +3 -4
- package/dist/esm/base/controllers/factory/controller.js +0 -1
- package/dist/esm/base/controllers/factory/controller.js.map +1 -1
- package/dist/esm/base/controllers/factory/crud/abstract.d.ts +3 -4
- package/dist/esm/base/controllers/factory/crud/abstract.js.map +1 -1
- package/dist/esm/base/controllers/factory/definition.d.ts +21 -1
- package/dist/esm/base/controllers/factory/definition.js +45 -31
- package/dist/esm/base/controllers/factory/definition.js.map +1 -1
- package/dist/esm/base/controllers/factory/index.d.ts +1 -0
- package/dist/esm/base/controllers/factory/index.js +1 -0
- package/dist/esm/base/controllers/factory/index.js.map +1 -1
- package/dist/esm/base/controllers/factory/injection.d.ts +38 -0
- package/dist/esm/base/controllers/factory/injection.js +54 -0
- package/dist/esm/base/controllers/factory/injection.js.map +1 -0
- package/dist/esm/base/controllers/rest/abstract.js +1 -1
- package/dist/esm/base/controllers/rest/abstract.js.map +1 -1
- package/dist/esm/base/controllers/rest/base.d.ts +3 -3
- package/dist/esm/base/controllers/rest/base.js.map +1 -1
- package/dist/esm/base/datasources/abstract.d.ts +4 -92
- package/dist/esm/base/datasources/abstract.js +3 -217
- package/dist/esm/base/datasources/abstract.js.map +1 -1
- package/dist/esm/base/datasources/common/types.d.ts +2 -2
- package/dist/esm/base/datasources/common/types.js.map +1 -1
- package/dist/esm/base/datasources/index.d.ts +1 -0
- package/dist/esm/base/datasources/index.js +1 -0
- package/dist/esm/base/datasources/index.js.map +1 -1
- package/dist/esm/base/datasources/root.d.ts +107 -0
- package/dist/esm/base/datasources/root.js +237 -0
- package/dist/esm/base/datasources/root.js.map +1 -0
- package/dist/esm/base/events/event-bus.js.map +1 -1
- package/dist/esm/base/metadata/index.d.ts +1 -1
- package/dist/esm/base/metadata/index.js +1 -1
- package/dist/esm/base/metadata/injectors.d.ts +1 -1
- package/dist/esm/base/metadata/persistents/datasource.d.ts +21 -0
- package/dist/esm/base/metadata/persistents/datasource.js +46 -0
- package/dist/esm/base/metadata/persistents/datasource.js.map +1 -0
- package/dist/esm/base/metadata/persistents/index.d.ts +5 -0
- package/dist/esm/base/metadata/persistents/index.js +5 -0
- package/dist/esm/base/metadata/persistents/index.js.map +1 -0
- package/dist/esm/base/metadata/persistents/model.d.ts +18 -0
- package/dist/esm/base/metadata/persistents/model.js +64 -0
- package/dist/esm/base/metadata/persistents/model.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/index.d.ts +19 -0
- package/dist/esm/base/metadata/persistents/repository/index.js +32 -0
- package/dist/esm/base/metadata/persistents/repository/index.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/injection.d.ts +15 -0
- package/dist/esm/base/metadata/persistents/repository/injection.js +64 -0
- package/dist/esm/base/metadata/persistents/repository/injection.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/resolve.d.ts +15 -0
- package/dist/esm/base/metadata/persistents/repository/resolve.js +76 -0
- package/dist/esm/base/metadata/persistents/repository/resolve.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/validate.d.ts +15 -0
- package/dist/esm/base/metadata/persistents/repository/validate.js +50 -0
- package/dist/esm/base/metadata/persistents/repository/validate.js.map +1 -0
- package/dist/esm/base/models/common/utilities.d.ts +1 -1
- package/dist/esm/base/repositories/common/response-reader.d.ts +30 -0
- package/dist/esm/base/repositories/common/response-reader.js +53 -0
- package/dist/esm/base/repositories/common/response-reader.js.map +1 -1
- package/dist/esm/base/repositories/common/types/contracts.d.ts +2 -2
- package/dist/esm/base/repositories/common/types/contracts.js.map +1 -1
- package/dist/esm/base/repositories/common/types/options.d.ts +2 -2
- package/dist/esm/base/repositories/common/types/options.js.map +1 -1
- package/dist/esm/base/repositories/common/types/query.d.ts +6 -15
- package/dist/esm/base/repositories/common/types/query.js.map +1 -1
- package/dist/esm/base/repositories/core/abstract.d.ts +6 -6
- package/dist/esm/base/repositories/core/abstract.js.map +1 -1
- package/dist/esm/base/repositories/query-schemas/index.js +7 -0
- package/dist/esm/base/repositories/query-schemas/index.js.map +1 -1
- package/dist/esm/helpers/inversion/common/types/model.d.ts +1 -1
- package/dist/esm/helpers/inversion/common/types/model.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/artifact.mixin.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/artifact.mixin.js +1 -0
- package/dist/esm/helpers/inversion/mixins/artifact.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/controllers/controller.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/controllers/controller.js +1 -0
- package/dist/esm/helpers/inversion/mixins/controllers/controller.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/controllers/grpc.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/controllers/grpc.js +1 -0
- package/dist/esm/helpers/inversion/mixins/controllers/grpc.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/controllers/rest.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/controllers/rest.js +1 -0
- package/dist/esm/helpers/inversion/mixins/controllers/rest.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/datasource.mixin.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/datasource.mixin.js +1 -0
- package/dist/esm/helpers/inversion/mixins/datasource.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/model.mixin.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/model.mixin.js +1 -0
- package/dist/esm/helpers/inversion/mixins/model.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/repository.mixin.d.ts +9 -8
- package/dist/esm/helpers/inversion/mixins/repository.mixin.js +6 -6
- package/dist/esm/helpers/inversion/mixins/repository.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/registry.d.ts +26 -26
- package/dist/esm/helpers/inversion/registry.js.map +1 -1
- package/dist/esm/helpers/singleton-realm.js +5 -4
- package/dist/esm/helpers/singleton-realm.js.map +1 -1
- package/dist/esm/metadata.d.ts +1 -1
- package/dist/esm/metadata.js +1 -1
- package/dist/esm/repository.d.ts +1 -0
- package/dist/esm/repository.js +1 -0
- package/dist/esm/repository.js.map +1 -1
- package/dist/esm/utilities/index.d.ts +1 -0
- package/dist/esm/utilities/index.js +1 -0
- package/dist/esm/utilities/index.js.map +1 -1
- package/dist/esm/utilities/toggle.utility.d.ts +22 -0
- package/dist/esm/utilities/toggle.utility.js +16 -0
- package/dist/esm/utilities/toggle.utility.js.map +1 -0
- package/package.json +5 -5
- package/dist/esm/base/metadata/persistents.d.ts +0 -54
- package/dist/esm/base/metadata/persistents.js +0 -302
- package/dist/esm/base/metadata/persistents.js.map +0 -1
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { MetadataRegistry } from '../../../../helpers/inversion/index.js';
|
|
2
|
+
import { applyRepositoryMetadata, inheritRepositoryMetadata } from './resolve.js';
|
|
3
|
+
/**
|
|
4
|
+
* Class decorator that registers a repository and binds it to a model (or, for a remote repository, only a datasource). Called without arguments on a subclass it reuses the type, model and datasource of its nearest decorated parent; registration options are not inherited.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import { repository } from '@venizia/ignis';
|
|
9
|
+
* import { DefaultCRUDRepository } from '@venizia/ignis-connectors/postgres';
|
|
10
|
+
* import { AppDataSource } from './app.datasource';
|
|
11
|
+
* import { Note, noteTable } from './note.model';
|
|
12
|
+
*
|
|
13
|
+
* export @repository({ model: Note, dataSource: AppDataSource })
|
|
14
|
+
* class NoteRepository extends DefaultCRUDRepository<typeof noteTable> {}
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export const repository = (metadata) => {
|
|
18
|
+
return (target) => {
|
|
19
|
+
const registry = MetadataRegistry.getInstance();
|
|
20
|
+
if (!metadata) {
|
|
21
|
+
applyRepositoryMetadata({
|
|
22
|
+
metadata: inheritRepositoryMetadata({ target, registry }),
|
|
23
|
+
registration: {},
|
|
24
|
+
target,
|
|
25
|
+
registry,
|
|
26
|
+
});
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
applyRepositoryMetadata({ metadata, registration: metadata, target, registry });
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/base/metadata/persistents/repository/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAIvD,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,WAAW,CAAC;AAE/E;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAIxB,QAAiD,EACjC,EAAE;IAClB,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,MAAM,QAAQ,GAAG,gBAAgB,CAAC,WAAW,EAAE,CAAC;QAEhD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,uBAAuB,CAAC;gBACtB,QAAQ,EAAE,yBAAyB,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;gBACzD,YAAY,EAAE,EAAE;gBAChB,MAAM;gBACN,QAAQ;aACT,CAAC,CAAC;YAEH,OAAO;QACT,CAAC;QAED,uBAAuB,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAClF,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { MetadataRegistry } from '@/helpers/inversion';\nimport type { TRepositoryMetadata } from '@/helpers/inversion';\nimport type { IDataSource } from '../../../datasources';\nimport type { AbstractEntity } from '../../../models';\nimport { applyRepositoryMetadata, inheritRepositoryMetadata } from './resolve';\n\n/**\n * Class decorator that registers a repository and binds it to a model (or, for a remote repository, only a datasource). Called without arguments on a subclass it reuses the type, model and datasource of its nearest decorated parent; registration options are not inherited.\n *\n * @example\n * ```typescript\n * import { repository } from '@venizia/ignis';\n * import { DefaultCRUDRepository } from '@venizia/ignis-connectors/postgres';\n * import { AppDataSource } from './app.datasource';\n * import { Note, noteTable } from './note.model';\n *\n * export @repository({ model: Note, dataSource: AppDataSource })\n * class NoteRepository extends DefaultCRUDRepository<typeof noteTable> {}\n * ```\n */\nexport const repository = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(\n metadata?: TRepositoryMetadata<Model, DataSource>,\n): ClassDecorator => {\n return (target) => {\n const registry = MetadataRegistry.getInstance();\n\n if (!metadata) {\n applyRepositoryMetadata({\n metadata: inheritRepositoryMetadata({ target, registry }),\n registration: {},\n target,\n registry,\n });\n\n return;\n }\n\n applyRepositoryMetadata({ metadata, registration: metadata, target, registry });\n };\n};\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import type { TRepositoryMetadata } from '../../../../helpers/inversion/index.js';
|
|
3
|
+
import type { MetadataRegistry } from '../../../../helpers/inversion/index.js';
|
|
4
|
+
/**
|
|
5
|
+
* Auto-injects dataSource at constructor param[0] unless explicit @inject exists. A class is injected
|
|
6
|
+
* by the class itself, so the container reads the key its registration recorded: a pinned
|
|
7
|
+
* `binding` and a minified class name both resolve. Only a string reference is a key.
|
|
8
|
+
*/
|
|
9
|
+
export declare const registerDataSourceInjection: (opts: {
|
|
10
|
+
target: Function;
|
|
11
|
+
registry: MetadataRegistry;
|
|
12
|
+
dataSourceRef: TRepositoryMetadata["dataSource"];
|
|
13
|
+
resolvedDataSource: string | Function;
|
|
14
|
+
}) => void;
|
|
15
|
+
//# sourceMappingURL=injection.d.ts.map
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import { BindingNamespaces } from '../../../../common/bindings.js';
|
|
3
|
+
import { BindingKeys, MetadataKeys } from '../../../../helpers/inversion/index.js';
|
|
4
|
+
import { ResolverUtility } from '@venizia/ignis-helpers/common';
|
|
5
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
6
|
+
import { isDataSourceClass } from '../../../datasources/index.js';
|
|
7
|
+
import { validateFirstConstructorParameter } from './validate.js';
|
|
8
|
+
/**
|
|
9
|
+
* Auto-injects dataSource at constructor param[0] unless explicit @inject exists. A class is injected
|
|
10
|
+
* by the class itself, so the container reads the key its registration recorded: a pinned
|
|
11
|
+
* `binding` and a minified class name both resolve. Only a string reference is a key.
|
|
12
|
+
*/
|
|
13
|
+
export const registerDataSourceInjection = (opts) => {
|
|
14
|
+
const { target, registry, dataSourceRef, resolvedDataSource } = opts;
|
|
15
|
+
// Own metadata only: `getInjectMetadata` walks the prototype chain, so a repository extending another @repository class would see the BASE's injection at param[0] and silently resolve the base's dataSource.
|
|
16
|
+
const ownInjects = Reflect.getOwnMetadata(MetadataKeys.INJECT, target);
|
|
17
|
+
const injectAtIndex0 = ownInjects?.find((entry) => entry?.index === 0);
|
|
18
|
+
if (injectAtIndex0) {
|
|
19
|
+
// `@inject({ target })` carries no key; read the one recorded on the class. The function form
|
|
20
|
+
// resolves through the same helper the container uses, so both paths read one class.
|
|
21
|
+
const injectedTarget = injectAtIndex0.target
|
|
22
|
+
? ResolverUtility.resolveInjectTarget({ target: injectAtIndex0.target })
|
|
23
|
+
: undefined;
|
|
24
|
+
const injectKey = injectAtIndex0.key ??
|
|
25
|
+
(injectedTarget ? registry.getBindingKey({ target: injectedTarget }) : undefined);
|
|
26
|
+
// A class is judged by its brand: its key may sit under any namespace a `binding` pinned, and
|
|
27
|
+
// a provisional key may still change at registration. Only a bare key is judged by its prefix.
|
|
28
|
+
const isDataSourceTarget = injectedTarget
|
|
29
|
+
? isDataSourceClass(injectedTarget)
|
|
30
|
+
: typeof injectKey === 'string' && injectKey.startsWith(`${BindingNamespaces.DATASOURCE}.`);
|
|
31
|
+
if (!isDataSourceTarget) {
|
|
32
|
+
throw getError({
|
|
33
|
+
message: `[@repository][${target.name}] Invalid constructor | First parameter must be a DataSource | Found @inject with key: '${String(injectKey)}' | Expected a key starting with '${BindingNamespaces.DATASOURCE}.' or a DataSource class`,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
// Checked only when this decorator writes the injection: an explicit @inject decides for itself.
|
|
39
|
+
// An interface emits `Object` and a type-only class import emits `Function` under tsc (`Object`
|
|
40
|
+
// under bun); neither names the class, so neither is judged.
|
|
41
|
+
const firstParamType = Reflect.getMetadata('design:paramtypes', target)?.[0];
|
|
42
|
+
if (firstParamType && firstParamType !== Object && firstParamType !== Function) {
|
|
43
|
+
validateFirstConstructorParameter({ target, firstParamType, resolvedDataSource });
|
|
44
|
+
}
|
|
45
|
+
// The inherited list is the base repository's own, and setInjectMetadata may write straight into it.
|
|
46
|
+
if (!ownInjects) {
|
|
47
|
+
Reflect.defineMetadata(MetadataKeys.INJECT, [...(registry.getInjectMetadata({ target }) ?? [])], target);
|
|
48
|
+
}
|
|
49
|
+
const derivedKey = BindingKeys.build({
|
|
50
|
+
namespace: BindingNamespaces.DATASOURCE,
|
|
51
|
+
key: typeof resolvedDataSource === 'string' ? resolvedDataSource : resolvedDataSource.name,
|
|
52
|
+
});
|
|
53
|
+
// The class first, decided when the repository is resolved: by then any registration - decorated,
|
|
54
|
+
// `bindingList()`, or `dataSource(X, { binding })` - has recorded its key on the class. The derived
|
|
55
|
+
// key is the fallback for a class nothing recorded, bound by hand under exactly that key.
|
|
56
|
+
registry.setInjectMetadata({
|
|
57
|
+
target,
|
|
58
|
+
index: 0,
|
|
59
|
+
metadata: typeof dataSourceRef === 'string'
|
|
60
|
+
? { key: derivedKey, index: 0, isOptional: false }
|
|
61
|
+
: { target: dataSourceRef, key: derivedKey, index: 0, isOptional: false },
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
//# sourceMappingURL=injection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"injection.js","sourceRoot":"","sources":["../../../../../../src/base/metadata/persistents/repository/injection.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAE1B,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEhE,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEhE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAA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\n\nimport { BindingNamespaces } from '@/common/bindings';\nimport type { TRepositoryMetadata } from '@/helpers/inversion';\nimport { BindingKeys, MetadataKeys } from '@/helpers/inversion';\nimport type { MetadataRegistry } from '@/helpers/inversion';\nimport { ResolverUtility } from '@venizia/ignis-helpers/common';\nimport type { IInjectMetadata } from '@venizia/ignis-inversion';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { isDataSourceClass } from '../../../datasources';\nimport { validateFirstConstructorParameter } from './validate';\n\n/**\n * Auto-injects dataSource at constructor param[0] unless explicit @inject exists. A class is injected\n * by the class itself, so the container reads the key its registration recorded: a pinned\n * `binding` and a minified class name both resolve. Only a string reference is a key.\n */\nexport const registerDataSourceInjection = (opts: {\n target: Function;\n registry: MetadataRegistry;\n dataSourceRef: TRepositoryMetadata['dataSource'];\n resolvedDataSource: string | Function;\n}): void => {\n const { target, registry, dataSourceRef, resolvedDataSource } = opts;\n\n // Own metadata only: `getInjectMetadata` walks the prototype chain, so a repository extending another @repository class would see the BASE's injection at param[0] and silently resolve the base's dataSource.\n const ownInjects: IInjectMetadata[] | undefined = Reflect.getOwnMetadata(\n MetadataKeys.INJECT,\n target,\n );\n const injectAtIndex0 = ownInjects?.find((entry) => entry?.index === 0);\n\n if (injectAtIndex0) {\n // `@inject({ target })` carries no key; read the one recorded on the class. The function form\n // resolves through the same helper the container uses, so both paths read one class.\n const injectedTarget = injectAtIndex0.target\n ? ResolverUtility.resolveInjectTarget({ target: injectAtIndex0.target })\n : undefined;\n const injectKey =\n injectAtIndex0.key ??\n (injectedTarget ? registry.getBindingKey({ target: injectedTarget }) : undefined);\n\n // A class is judged by its brand: its key may sit under any namespace a `binding` pinned, and\n // a provisional key may still change at registration. Only a bare key is judged by its prefix.\n const isDataSourceTarget = injectedTarget\n ? isDataSourceClass(injectedTarget)\n : typeof injectKey === 'string' && injectKey.startsWith(`${BindingNamespaces.DATASOURCE}.`);\n\n if (!isDataSourceTarget) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | First parameter must be a DataSource | Found @inject with key: '${String(injectKey)}' | Expected a key starting with '${BindingNamespaces.DATASOURCE}.' or a DataSource class`,\n });\n }\n\n return;\n }\n\n // Checked only when this decorator writes the injection: an explicit @inject decides for itself.\n // An interface emits `Object` and a type-only class import emits `Function` under tsc (`Object`\n // under bun); neither names the class, so neither is judged.\n const firstParamType = Reflect.getMetadata('design:paramtypes', target)?.[0];\n\n if (firstParamType && firstParamType !== Object && firstParamType !== Function) {\n validateFirstConstructorParameter({ target, firstParamType, resolvedDataSource });\n }\n\n // The inherited list is the base repository's own, and setInjectMetadata may write straight into it.\n if (!ownInjects) {\n Reflect.defineMetadata(\n MetadataKeys.INJECT,\n [...(registry.getInjectMetadata({ target }) ?? [])],\n target,\n );\n }\n\n const derivedKey = BindingKeys.build({\n namespace: BindingNamespaces.DATASOURCE,\n key: typeof resolvedDataSource === 'string' ? resolvedDataSource : resolvedDataSource.name,\n });\n\n // The class first, decided when the repository is resolved: by then any registration - decorated,\n // `bindingList()`, or `dataSource(X, { binding })` - has recorded its key on the class. The derived\n // key is the fallback for a class nothing recorded, bound by hand under exactly that key.\n registry.setInjectMetadata({\n target,\n index: 0,\n metadata:\n typeof dataSourceRef === 'string'\n ? { key: derivedKey, index: 0, isOptional: false }\n : { target: dataSourceRef, key: derivedKey, index: 0, isOptional: false },\n });\n};\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { IArtifactRegistrationOptions, MetadataRegistry, TRepositoryMetadata } from '../../../../helpers/inversion/index.js';
|
|
2
|
+
import type { IDataSource } from '../../../datasources/index.js';
|
|
3
|
+
import type { AbstractEntity } from '../../../models/index.js';
|
|
4
|
+
/** A bare `@repository()` on a subclass reuses the type, model and datasource its nearest decorated parent declared; the registration options (`binding`, `when`, ...) are never inherited, so the subclass registers under its own name. */
|
|
5
|
+
export declare const inheritRepositoryMetadata: (opts: {
|
|
6
|
+
target: Function;
|
|
7
|
+
registry: MetadataRegistry;
|
|
8
|
+
}) => TRepositoryMetadata;
|
|
9
|
+
export declare const applyRepositoryMetadata: <Model extends AbstractEntity = AbstractEntity, DataSource extends IDataSource = IDataSource>(opts: {
|
|
10
|
+
metadata: TRepositoryMetadata<Model, DataSource>;
|
|
11
|
+
registration: IArtifactRegistrationOptions;
|
|
12
|
+
target: Function;
|
|
13
|
+
registry: MetadataRegistry;
|
|
14
|
+
}) => void;
|
|
15
|
+
//# sourceMappingURL=resolve.d.ts.map
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { ArtifactTypes } from '../../../../helpers/inversion/index.js';
|
|
2
|
+
import { ClassResolver, ResolverUtility } from '@venizia/ignis-helpers/common';
|
|
3
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
4
|
+
import { RepositoryTypes } from '../../../repositories/common/constants.js';
|
|
5
|
+
import { injectable, InjectableUtility } from '../../injectable.js';
|
|
6
|
+
import { registerDataSourceInjection } from './injection.js';
|
|
7
|
+
import { validateRepositoryMetadata } from './validate.js';
|
|
8
|
+
/** Resolves repository metadata and registers bindings for schema auto-discovery. */
|
|
9
|
+
const resolveRepositoryMetadata = (opts) => {
|
|
10
|
+
const { metadata, target, registry } = opts;
|
|
11
|
+
validateRepositoryMetadata({ metadata, target });
|
|
12
|
+
const resolvedDataSource = ClassResolver.resolveClass({ ref: metadata.dataSource });
|
|
13
|
+
if (!resolvedDataSource) {
|
|
14
|
+
throw getError({
|
|
15
|
+
message: `[@repository][${target.name}] The dataSource resolver returned nothing at decoration time | An import cycle leaves the datasource class undefined here; import it without the cycle, or name it as a string`,
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
// No model, so no binding: the datasource owns no schema through this repository.
|
|
19
|
+
if (metadata.type === RepositoryTypes.REMOTE) {
|
|
20
|
+
registerDataSourceInjection({
|
|
21
|
+
target,
|
|
22
|
+
registry,
|
|
23
|
+
dataSourceRef: metadata.dataSource,
|
|
24
|
+
resolvedDataSource,
|
|
25
|
+
});
|
|
26
|
+
return {
|
|
27
|
+
type: RepositoryTypes.REMOTE,
|
|
28
|
+
dataSource: resolvedDataSource,
|
|
29
|
+
operationScope: metadata.operationScope,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const resolvedModel = ResolverUtility.resolveValue({ value: metadata.model });
|
|
33
|
+
registry.registerRepositoryBinding({
|
|
34
|
+
repository: target,
|
|
35
|
+
model: resolvedModel,
|
|
36
|
+
dataSource: resolvedDataSource,
|
|
37
|
+
});
|
|
38
|
+
registerDataSourceInjection({
|
|
39
|
+
target,
|
|
40
|
+
registry,
|
|
41
|
+
dataSourceRef: metadata.dataSource,
|
|
42
|
+
resolvedDataSource,
|
|
43
|
+
});
|
|
44
|
+
return {
|
|
45
|
+
type: RepositoryTypes.MODEL,
|
|
46
|
+
model: resolvedModel,
|
|
47
|
+
dataSource: resolvedDataSource,
|
|
48
|
+
operationScope: metadata.operationScope,
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
/** A bare `@repository()` on a subclass reuses the type, model and datasource its nearest decorated parent declared; the registration options (`binding`, `when`, ...) are never inherited, so the subclass registers under its own name. */
|
|
52
|
+
export const inheritRepositoryMetadata = (opts) => {
|
|
53
|
+
// Own metadata does not exist yet at decoration time, so this read walks the prototype chain.
|
|
54
|
+
const inherited = opts.registry.getRepositoryMetadata({ target: opts.target });
|
|
55
|
+
if (!inherited) {
|
|
56
|
+
throw getError({
|
|
57
|
+
message: `[@repository][${opts.target.name}] No metadata given and no decorated repository above it in the prototype chain | pass { model, dataSource } or decorate the parent`,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
if (inherited.type === RepositoryTypes.REMOTE) {
|
|
61
|
+
const { type, dataSource, operationScope } = inherited;
|
|
62
|
+
return { type, dataSource, operationScope };
|
|
63
|
+
}
|
|
64
|
+
const { type, model: parentModel, dataSource, operationScope } = inherited;
|
|
65
|
+
return { type, model: parentModel, dataSource, operationScope };
|
|
66
|
+
};
|
|
67
|
+
export const applyRepositoryMetadata = (opts) => {
|
|
68
|
+
const { metadata, registration, target, registry } = opts;
|
|
69
|
+
injectable({
|
|
70
|
+
type: ArtifactTypes.REPOSITORY,
|
|
71
|
+
...InjectableUtility.pickRegistrationOptions({ metadata: registration }),
|
|
72
|
+
})(target);
|
|
73
|
+
const resolved = resolveRepositoryMetadata({ metadata, target, registry });
|
|
74
|
+
registry.setRepositoryMetadata({ target, metadata: { ...metadata, _resolved: resolved } });
|
|
75
|
+
};
|
|
76
|
+
//# sourceMappingURL=resolve.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../../../../../src/base/metadata/persistents/repository/resolve.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAExD,qFAAqF;AACrF,MAAM,yBAAyB,GAAG,CAGhC,IAID,EAAkD,EAAE;IACnD,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IAE5C,0BAA0B,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;IAEjD,MAAM,kBAAkB,GAAG,aAAa,CAAC,YAAY,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;IAEpF,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACxB,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,iBAAiB,MAAM,CAAC,IAAI,iLAAi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C;IACL,CAAC;IAED,IAAI,SAAS,CAAC,IAAI,KAAK,eAAe,CAAC,MAAM,EAAE,CAAC;QAC9C,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,cAAc,EAAE,GAAG,SAAS,CAAC;QAEvD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,cAAc,EAAE,CAAC;IAC9C,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,cAAc,EAAE,GAAG,SAAS,CAAC;IAE3E,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,cAAc,EAAE,CAAC;AAClE,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAGrC,IAKD,EAAQ,EAAE;IACT,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IAE1D,UAAU,CAAC;QACT,IAAI,EAAE,aAAa,CAAC,UAAU;QAC9B,GAAG,iBAAiB,CAAC,uBAAuB,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;KACzE,CAAC,CAAC,MAAM,CAAC,CAAC;IAEX,MAAM,QAAQ,GAAG,yBAAyB,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAE3E,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,GAAG,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;AAC7F,CAAC,CAAC","sourcesContent":["import type {\n IArtifactRegistrationOptions,\n IResolvedRepositoryMetadata,\n MetadataRegistry,\n TRepositoryMetadata,\n} from '@/helpers/inversion';\nimport { ArtifactTypes } from '@/helpers/inversion';\nimport { ClassResolver, ResolverUtility } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IDataSource } from '../../../datasources';\nimport type { AbstractEntity } from '../../../models';\nimport { RepositoryTypes } from '../../../repositories/common/constants';\nimport { injectable, InjectableUtility } from '../../injectable';\nimport { registerDataSourceInjection } from './injection';\nimport { validateRepositoryMetadata } from './validate';\n\n/** Resolves repository metadata and registers bindings for schema auto-discovery. */\nconst resolveRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n target: Function;\n registry: MetadataRegistry;\n}): IResolvedRepositoryMetadata<Model, DataSource> => {\n const { metadata, target, registry } = opts;\n\n validateRepositoryMetadata({ metadata, target });\n\n const resolvedDataSource = ClassResolver.resolveClass({ ref: metadata.dataSource });\n\n if (!resolvedDataSource) {\n throw getError({\n message: `[@repository][${target.name}] The dataSource resolver returned nothing at decoration time | An import cycle leaves the datasource class undefined here; import it without the cycle, or name it as a string`,\n });\n }\n\n // No model, so no binding: the datasource owns no schema through this repository.\n if (metadata.type === RepositoryTypes.REMOTE) {\n registerDataSourceInjection({\n target,\n registry,\n dataSourceRef: metadata.dataSource,\n resolvedDataSource,\n });\n\n return {\n type: RepositoryTypes.REMOTE,\n dataSource: resolvedDataSource,\n operationScope: metadata.operationScope,\n };\n }\n\n const resolvedModel = ResolverUtility.resolveValue({ value: metadata.model });\n\n registry.registerRepositoryBinding({\n repository: target,\n model: resolvedModel,\n dataSource: resolvedDataSource,\n });\n\n registerDataSourceInjection({\n target,\n registry,\n dataSourceRef: metadata.dataSource,\n resolvedDataSource,\n });\n\n return {\n type: RepositoryTypes.MODEL,\n model: resolvedModel,\n dataSource: resolvedDataSource,\n operationScope: metadata.operationScope,\n };\n};\n\n/** A bare `@repository()` on a subclass reuses the type, model and datasource its nearest decorated parent declared; the registration options (`binding`, `when`, ...) are never inherited, so the subclass registers under its own name. */\nexport const inheritRepositoryMetadata = (opts: {\n target: Function;\n registry: MetadataRegistry;\n}): TRepositoryMetadata => {\n // Own metadata does not exist yet at decoration time, so this read walks the prototype chain.\n const inherited = opts.registry.getRepositoryMetadata({ target: opts.target });\n\n if (!inherited) {\n throw getError({\n message: `[@repository][${opts.target.name}] No metadata given and no decorated repository above it in the prototype chain | pass { model, dataSource } or decorate the parent`,\n });\n }\n\n if (inherited.type === RepositoryTypes.REMOTE) {\n const { type, dataSource, operationScope } = inherited;\n\n return { type, dataSource, operationScope };\n }\n\n const { type, model: parentModel, dataSource, operationScope } = inherited;\n\n return { type, model: parentModel, dataSource, operationScope };\n};\n\nexport const applyRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n registration: IArtifactRegistrationOptions;\n target: Function;\n registry: MetadataRegistry;\n}): void => {\n const { metadata, registration, target, registry } = opts;\n\n injectable({\n type: ArtifactTypes.REPOSITORY,\n ...InjectableUtility.pickRegistrationOptions({ metadata: registration }),\n })(target);\n\n const resolved = resolveRepositoryMetadata({ metadata, target, registry });\n\n registry.setRepositoryMetadata({ target, metadata: { ...metadata, _resolved: resolved } });\n};\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { TRepositoryMetadata } from '../../../../helpers/inversion/index.js';
|
|
2
|
+
import type { IDataSource } from '../../../datasources/index.js';
|
|
3
|
+
import type { AbstractEntity } from '../../../models/index.js';
|
|
4
|
+
/** Mirrors the `TRepositoryMetadata` union for JavaScript callers: a known type, a dataSource always, a model exactly when the type is RepositoryTypes.MODEL. */
|
|
5
|
+
export declare const validateRepositoryMetadata: <Model extends AbstractEntity = AbstractEntity, DataSource extends IDataSource = IDataSource>(opts: {
|
|
6
|
+
metadata: TRepositoryMetadata<Model, DataSource>;
|
|
7
|
+
target: Function;
|
|
8
|
+
}) => void;
|
|
9
|
+
/** Asserts the constructor's first parameter is a datasource class (`AbstractDataSource` or the `DataSourceRoot` it extends) compatible with what @repository declared. */
|
|
10
|
+
export declare const validateFirstConstructorParameter: (opts: {
|
|
11
|
+
target: Function;
|
|
12
|
+
firstParamType: Function;
|
|
13
|
+
resolvedDataSource: string | Function;
|
|
14
|
+
}) => void;
|
|
15
|
+
//# sourceMappingURL=validate.d.ts.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
2
|
+
import { isDataSourceClass } from '../../../datasources/index.js';
|
|
3
|
+
import { RepositoryTypes } from '../../../repositories/common/constants.js';
|
|
4
|
+
/** Mirrors the `TRepositoryMetadata` union for JavaScript callers: a known type, a dataSource always, a model exactly when the type is RepositoryTypes.MODEL. */
|
|
5
|
+
export const validateRepositoryMetadata = (opts) => {
|
|
6
|
+
const { metadata, target } = opts;
|
|
7
|
+
const type = metadata.type ?? RepositoryTypes.MODEL;
|
|
8
|
+
if (!RepositoryTypes.isValid(type)) {
|
|
9
|
+
throw getError({
|
|
10
|
+
message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Unknown 'type': ${type} | Expected one of: ${[...RepositoryTypes.SCHEME_SET].join(', ')}`,
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
if (type === RepositoryTypes.MODEL && !metadata.model) {
|
|
14
|
+
throw getError({
|
|
15
|
+
message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'model'`,
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
if (type === RepositoryTypes.REMOTE && metadata.model) {
|
|
19
|
+
throw getError({
|
|
20
|
+
message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | A '${RepositoryTypes.REMOTE}' repository takes no 'model'`,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
if (!metadata.dataSource) {
|
|
24
|
+
throw getError({
|
|
25
|
+
message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'dataSource'`,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/** Asserts the constructor's first parameter is a datasource class (`AbstractDataSource` or the `DataSourceRoot` it extends) compatible with what @repository declared. */
|
|
30
|
+
export const validateFirstConstructorParameter = (opts) => {
|
|
31
|
+
const { target, firstParamType, resolvedDataSource } = opts;
|
|
32
|
+
// NOT `instanceof`: two copies of this package give two `DataSourceRoot` classes and the
|
|
33
|
+
// check would be false across them, rejecting a perfectly valid repository at import time.
|
|
34
|
+
const isDataSourceType = isDataSourceClass(firstParamType);
|
|
35
|
+
if (!isDataSourceType) {
|
|
36
|
+
throw getError({
|
|
37
|
+
message: `[@repository][${target.name}] Invalid constructor | First parameter must extend AbstractDataSource (or DataSourceRoot) | Received: '${firstParamType.name}'`,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
if (typeof resolvedDataSource !== 'function') {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const isCompatible = firstParamType === resolvedDataSource || resolvedDataSource.prototype instanceof firstParamType;
|
|
44
|
+
if (!isCompatible) {
|
|
45
|
+
throw getError({
|
|
46
|
+
message: `[@repository][${target.name}] Invalid constructor | Type mismatch | Constructor expects '${firstParamType.name}' but @repository specifies '${resolvedDataSource.name}'`,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
//# sourceMappingURL=validate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validate.js","sourceRoot":"","sources":["../../../../../../src/base/metadata/persistents/repository/validate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAEzE,iKAAiK;AACjK,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAGxC,IAGD,EAAQ,EAAE;IACT,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAClC,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,IAAI,eAAe,CAAC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SACvK,CAAC,CAAC;IACL,CAAC;IAED,IAAI,OAAO,kBAAkB,KAAK,UAAU,EAAE,CAAC;QAC7C,OAAO;IACT,CAAC;IAED,MAAM,YAAY,GAChB,cAAc,KAAK,kBAAkB,IAAI,kBAAkB,CAAC,SAAS,YAAY,cAAc,CAAC;IAElG,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,iBAAiB,MAAM,CAAC,IAAI,gEAAgE,cAAc,CAAC,IAAI,gCAAgC,kBAAkB,CAAC,IAAI,GAAG;SACnL,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC","sourcesContent":["import type { TRepositoryMetadata } from '@/helpers/inversion';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IDataSource } from '../../../datasources';\nimport { isDataSourceClass } from '../../../datasources';\nimport type { AbstractEntity } from '../../../models';\nimport { RepositoryTypes } from '../../../repositories/common/constants';\n\n/** Mirrors the `TRepositoryMetadata` union for JavaScript callers: a known type, a dataSource always, a model exactly when the type is RepositoryTypes.MODEL. */\nexport const validateRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n target: Function;\n}): void => {\n const { metadata, target } = opts;\n const type = metadata.type ?? RepositoryTypes.MODEL;\n\n if (!RepositoryTypes.isValid(type)) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Unknown 'type': ${type} | Expected one of: ${[...RepositoryTypes.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (type === RepositoryTypes.MODEL && !metadata.model) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'model'`,\n });\n }\n\n if (type === RepositoryTypes.REMOTE && metadata.model) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | A '${RepositoryTypes.REMOTE}' repository takes no 'model'`,\n });\n }\n\n if (!metadata.dataSource) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'dataSource'`,\n });\n }\n};\n\n/** Asserts the constructor's first parameter is a datasource class (`AbstractDataSource` or the `DataSourceRoot` it extends) compatible with what @repository declared. */\nexport const validateFirstConstructorParameter = (opts: {\n target: Function;\n firstParamType: Function;\n resolvedDataSource: string | Function;\n}): void => {\n const { target, firstParamType, resolvedDataSource } = opts;\n\n // NOT `instanceof`: two copies of this package give two `DataSourceRoot` classes and the\n // check would be false across them, rejecting a perfectly valid repository at import time.\n const isDataSourceType = isDataSourceClass(firstParamType);\n\n if (!isDataSourceType) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | First parameter must extend AbstractDataSource (or DataSourceRoot) | Received: '${firstParamType.name}'`,\n });\n }\n\n if (typeof resolvedDataSource !== 'function') {\n return;\n }\n\n const isCompatible =\n firstParamType === resolvedDataSource || resolvedDataSource.prototype instanceof firstParamType;\n\n if (!isCompatible) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | Type mismatch | Constructor expects '${firstParamType.name}' but @repository specifies '${resolvedDataSource.name}'`,\n });\n }\n};\n"]}
|
|
@@ -12,7 +12,7 @@ export declare class ModelUtility {
|
|
|
12
12
|
}): TEntityId;
|
|
13
13
|
static snakeToCamel<T extends z.ZodRawShape>(opts: {
|
|
14
14
|
shape: T;
|
|
15
|
-
}): z.ZodPipe<z.ZodPipe<z.ZodObject<{ -readonly [P in keyof T]: T[P]; }, z.core.$strip>, z.ZodTransform<
|
|
15
|
+
}): z.ZodPipe<z.ZodPipe<z.ZodObject<{ -readonly [P in keyof T]: T[P]; }, z.core.$strip>, z.ZodTransform<Record<string, unknown>, z.core.$InferObjectOutput<{ -readonly [P in keyof T]: T[P]; }, {}>>>, z.ZodObject<TCamelCaseKeys<T> extends infer T_1 ? { -readonly [P_1 in keyof T_1]: T_1[P_1]; } : never, z.core.$strip>>;
|
|
16
16
|
}
|
|
17
17
|
export {};
|
|
18
18
|
//# sourceMappingURL=utilities.d.ts.map
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import type { TJsonValue } from '@venizia/ignis-helpers/common';
|
|
1
2
|
import type { ApplicationError, TResponsedError } from '@venizia/ignis-helpers/core';
|
|
2
3
|
/**
|
|
3
4
|
* What an IGNIS server answers - `Content-Range`, the error envelope - read once, here, for every
|
|
4
5
|
* client of that server: the http connector, and a client that reads it without the connector.
|
|
5
6
|
*/
|
|
6
7
|
export declare class HttpResponseReader {
|
|
8
|
+
/** A content type that names JSON: `application/json`, `application/problem+json`, `application/ld+json`. */
|
|
9
|
+
static readonly JSON_CONTENT_TYPE_PATTERN: RegExp;
|
|
7
10
|
static isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
8
11
|
/** An empty string reads as absent, so a fallback still applies. */
|
|
9
12
|
static toText(value: unknown): string | undefined;
|
|
@@ -51,6 +54,33 @@ export declare class HttpResponseReader {
|
|
|
51
54
|
context: string;
|
|
52
55
|
rootKey?: string;
|
|
53
56
|
}): Promise<ApplicationError>;
|
|
57
|
+
/**
|
|
58
|
+
* The body as text: `''` for a 204 or an empty body. `response.json()` throws on those, and each client
|
|
59
|
+
* that reads a response has copied the guard.
|
|
60
|
+
*/
|
|
61
|
+
static readText(opts: {
|
|
62
|
+
response: Response;
|
|
63
|
+
}): Promise<string>;
|
|
64
|
+
/**
|
|
65
|
+
* The body of a success answer, by what it says it is: `null` for a 204 or an empty body, the parsed
|
|
66
|
+
* value when the content type names JSON (`application/json`, `application/problem+json`), the text itself
|
|
67
|
+
* for any other type (`text/plain`, `text/csv`). A body that claims JSON and is not is a `502` that names
|
|
68
|
+
* `context` (where it happened, e.g. `[Client][read] 200 | /tickets`), its size and its content type; its
|
|
69
|
+
* content stays out of the message, which a relaying server may pass to its own clients.
|
|
70
|
+
*/
|
|
71
|
+
static readBody(opts: {
|
|
72
|
+
response: Response;
|
|
73
|
+
context: string;
|
|
74
|
+
}): Promise<TJsonValue>;
|
|
75
|
+
/**
|
|
76
|
+
* The body as JSON whatever its content type says, `null` for a 204 or an empty body: for a route that
|
|
77
|
+
* answers JSON under a type a proxy rewrote. Errors as `readBody` does.
|
|
78
|
+
*/
|
|
79
|
+
static readJson(opts: {
|
|
80
|
+
response: Response;
|
|
81
|
+
context: string;
|
|
82
|
+
}): Promise<TJsonValue>;
|
|
83
|
+
private static parseJson;
|
|
54
84
|
/**
|
|
55
85
|
* A body the server marked with `x-response-extra` carries `extra` beside its rows. `body` is what
|
|
56
86
|
* the route answers without extras: the `{ count, data }` envelope when the count was asked for in
|
|
@@ -5,6 +5,8 @@ import { getError } from '@venizia/ignis-helpers/core';
|
|
|
5
5
|
* client of that server: the http connector, and a client that reads it without the connector.
|
|
6
6
|
*/
|
|
7
7
|
export class HttpResponseReader {
|
|
8
|
+
/** A content type that names JSON: `application/json`, `application/problem+json`, `application/ld+json`. */
|
|
9
|
+
static { this.JSON_CONTENT_TYPE_PATTERN = /json/i; }
|
|
8
10
|
static isPlainObject(value) {
|
|
9
11
|
return (!!value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype);
|
|
10
12
|
}
|
|
@@ -118,6 +120,57 @@ export class HttpResponseReader {
|
|
|
118
120
|
transform: ({ message }) => ({ ...message, text: displayText }),
|
|
119
121
|
});
|
|
120
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* The body as text: `''` for a 204 or an empty body. `response.json()` throws on those, and each client
|
|
125
|
+
* that reads a response has copied the guard.
|
|
126
|
+
*/
|
|
127
|
+
static async readText(opts) {
|
|
128
|
+
const { response } = opts;
|
|
129
|
+
return response.status === HTTP.ResultCodes.RS_2.NoContent ? '' : response.text();
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The body of a success answer, by what it says it is: `null` for a 204 or an empty body, the parsed
|
|
133
|
+
* value when the content type names JSON (`application/json`, `application/problem+json`), the text itself
|
|
134
|
+
* for any other type (`text/plain`, `text/csv`). A body that claims JSON and is not is a `502` that names
|
|
135
|
+
* `context` (where it happened, e.g. `[Client][read] 200 | /tickets`), its size and its content type; its
|
|
136
|
+
* content stays out of the message, which a relaying server may pass to its own clients.
|
|
137
|
+
*/
|
|
138
|
+
static async readBody(opts) {
|
|
139
|
+
const { response, context } = opts;
|
|
140
|
+
const text = await HttpResponseReader.readText({ response });
|
|
141
|
+
if (!text) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if (!HttpResponseReader.JSON_CONTENT_TYPE_PATTERN.test(response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? '')) {
|
|
145
|
+
return text;
|
|
146
|
+
}
|
|
147
|
+
return HttpResponseReader.parseJson({ text, response, context });
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* The body as JSON whatever its content type says, `null` for a 204 or an empty body: for a route that
|
|
151
|
+
* answers JSON under a type a proxy rewrote. Errors as `readBody` does.
|
|
152
|
+
*/
|
|
153
|
+
static async readJson(opts) {
|
|
154
|
+
const { response, context } = opts;
|
|
155
|
+
const text = await HttpResponseReader.readText({ response });
|
|
156
|
+
if (!text) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
return HttpResponseReader.parseJson({ text, response, context });
|
|
160
|
+
}
|
|
161
|
+
static parseJson(opts) {
|
|
162
|
+
const { text, response, context } = opts;
|
|
163
|
+
try {
|
|
164
|
+
return JSON.parse(text);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
const contentType = response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none';
|
|
168
|
+
throw getError({
|
|
169
|
+
statusCode: HTTP.ResultCodes.RS_5.BadGateway,
|
|
170
|
+
message: `${context} | The response body is not JSON (${text.length} chars, content-type: ${contentType})`,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
121
174
|
/**
|
|
122
175
|
* A body the server marked with `x-response-extra` carries `extra` beside its rows. `body` is what
|
|
123
176
|
* the route answers without extras: the `{ count, data }` envelope when the count was asked for in
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response-reader.js","sourceRoot":"","sources":["../../../../../src/base/repositories/common/response-reader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAC7B,MAAM,CAAC,aAAa,CAAC,KAAc;QACjC,OAAO,CACL,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,MAAM,CAAC,SAAS,CAC1F,CAAC;IACJ,CAAC;IAED,oEAAoE;IACpE,MAAM,CAAC,MAAM,CAAC,KAAc;QAC1B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACvE,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,iBAAiB,CAAC,IAExB;QACC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAExB,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;QAE7D,IAAI,KAAK,EAAE,CAAC;YACV,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,CAAC;QAED,MAAM,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;QAEpD,IAAI,WAAW,EAAE,CAAC;YAChB,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3C,CAA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IAAI,EAAE,WAAW,EAAE,CAAC;SAChE,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,SAAS,CAAC,IAAsD;QAIrE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAE1D,IACE,CAAC,QAAQ;YACT,CAAC,kBAAkB,CAAC,aAAa,CAAC,IAAI,CAAC;YACvC,CAAC,kBAAkB,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,EAC7C,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,CAAC;QAClB,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,GAAG,QAAQ,EAAE,GAAG,IAAI,CAAC;QAEpC,OAAO,EAAE,IAAI,EAAE,OAAO,IAAI,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,EAAE,CAAC;IACvF,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { ApplicationError, TResponsedError } from '@venizia/ignis-helpers/core';\n\n/**\n * What an IGNIS server answers - `Content-Range`, the error envelope - read once, here, for every\n * client of that server: the http connector, and a client that reads it without the connector.\n */\nexport class HttpResponseReader {\n static isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n !!value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype\n );\n }\n\n /** An empty string reads as absent, so a fallback still applies. */\n static toText(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n }\n\n /**\n * A `Content-Range` header as the IGNIS server writes it: `records 0-24/137` -> skip 0, total 137;\n * an empty page, `records *\\/137` -> total 137. Anything else, including an absent header or an\n * unknown total, is `undefined`.\n */\n static parseContentRange(opts: {\n header?: string | null;\n }): { skip?: number; total: number } | undefined {\n const { header } = opts;\n\n if (!header) {\n return undefined;\n }\n\n const range = header.match(/(\\d+)\\s*-\\s*(\\d+)\\s*\\/\\s*(\\d+)/);\n\n if (range) {\n return { skip: Number(range[1]), total: Number(range[3]) };\n }\n\n const unsatisfied = header.match(/\\*\\s*\\/\\s*(\\d+)/);\n\n if (unsatisfied) {\n return { total: Number(unsatisfied[1]) };\n }\n\n return undefined;\n }\n\n /**\n * The IGNIS error envelope - `{ message, statusCode, normalized: { text, code, args }, requestId,\n * extra, details }` - read off a parsed response body. A server configured with `error.rootKey`\n * wraps it under that key; pass the same `rootKey` to unwrap it. A body without that key, or with a\n * non-object under it (a proxy's `{ error: 'Bad Gateway' }`), is read as it stands.\n *\n * A body that is not a plain object yields `{}`; any other body yields its known fields, each\n * `undefined` when absent or mistyped. An empty string reads as absent.\n */\n static readErrorEnvelope(opts: { body: unknown; rootKey?: string }): TResponsedError {\n const { body, rootKey } = opts;\n\n const wrapped = rootKey && HttpResponseReader.isPlainObject(body) ? body[rootKey] : undefined;\n const envelope = HttpResponseReader.isPlainObject(wrapped) ? wrapped : body;\n\n if (!HttpResponseReader.isPlainObject(envelope)) {\n return {};\n }\n\n const { message, statusCode, normalized, requestId, extra, details } = envelope;\n const normalizedRecord = HttpResponseReader.isPlainObject(normalized) ? normalized : {};\n const { text, code, args } = normalizedRecord;\n\n return {\n message: HttpResponseReader.toText(message),\n statusCode: typeof statusCode === 'number' ? statusCode : undefined,\n normalized: {\n text: HttpResponseReader.toText(text),\n code: HttpResponseReader.toText(code),\n args: HttpResponseReader.isPlainObject(args) ? { ...args } : undefined,\n },\n requestId: HttpResponseReader.toText(requestId),\n extra: HttpResponseReader.isPlainObject(extra) ? { ...extra } : undefined,\n details: HttpResponseReader.isPlainObject(details) ? { ...details } : undefined,\n };\n }\n\n /** A failed response's envelope. A body that is not JSON yields `{}`, and the status alone still describes it. */\n static async readError(opts: { response: Response; rootKey?: string }): Promise<TResponsedError> {\n let text;\n\n try {\n const result = await opts.response.text();\n text = result;\n // eslint-disable-next-line venizia/no-silent-catch -- an unreadable body is read as no text; the status alone still describes the failure\n } catch {\n text = '';\n }\n\n let body: unknown;\n\n try {\n body = text ? JSON.parse(text) : undefined;\n // eslint-disable-next-line venizia/no-silent-catch -- a body that is not JSON yields `{}`; the status alone still describes the failure\n } catch {\n return {};\n }\n\n return HttpResponseReader.readErrorEnvelope({ body, rootKey: opts.rootKey });\n }\n\n /**\n * A failed response as the error the server threw: its status, code, args and text, and its\n * `extra` with the `requestId` added. `message` is `context` plus the server's text, for logs;\n * `normalized.text` stays the server's, for display - `HTTP <status>` when the server sent none.\n * `cause` is the server's `details.cause` - a 422's per-field issues, `{ path, message, code }`.\n *\n * `requestId` names the request this client made. A relaying server's `extra` carries the id of\n * the request it made upstream: it joins `upstreamRequestIds`, nearest first, at every hop.\n */\n static async toApplicationError(opts: {\n response: Response;\n /** Where it failed, for logs - e.g. `[HttpDataSource][read] 404 | /tickets`. */\n context: string;\n rootKey?: string;\n }): Promise<ApplicationError> {\n const { response, context, rootKey } = opts;\n const server = await HttpResponseReader.readError({ response, rootKey });\n const serverText = server.normalized?.text ?? server.message;\n const displayText = serverText ?? `HTTP ${response.status}`;\n\n const extra: Record<string, unknown> = { ...server.extra };\n\n if (server.requestId) {\n const upstreamRequestId = extra.requestId;\n extra.requestId = server.requestId;\n\n if (upstreamRequestId !== undefined && upstreamRequestId !== server.requestId) {\n const known = Array.isArray(extra.upstreamRequestIds) ? extra.upstreamRequestIds : [];\n extra.upstreamRequestIds = [upstreamRequestId, ...known];\n }\n }\n\n return getError({\n statusCode: response.status,\n message: serverText ? `${context} | ${serverText}` : context,\n messageCode: server.normalized?.code,\n messageArgs: server.normalized?.args,\n extra: Object.keys(extra).length > 0 ? extra : undefined,\n cause: server.details?.cause,\n transform: ({ message }) => ({ ...message, text: displayText }),\n });\n }\n\n /**\n * A body the server marked with `x-response-extra` carries `extra` beside its rows. `body` is what\n * the route answers without extras: the `{ count, data }` envelope when the count was asked for in\n * the body, the rows otherwise. Any other body is returned as it stands - an unmarked object is\n * never unwrapped, so a row that has `data` and `extra` columns of its own is never misread.\n */\n static readExtra(opts: { body: unknown; headers: Pick<Headers, 'has'> }): {\n body: unknown;\n extra?: Record<string, unknown>;\n } {\n const { body, headers } = opts;\n const isMarked = headers.has(HTTP.Headers.RESPONSE_EXTRA);\n\n if (\n !isMarked ||\n !HttpResponseReader.isPlainObject(body) ||\n !HttpResponseReader.isPlainObject(body.extra)\n ) {\n return { body };\n }\n\n const { extra, ...envelope } = body;\n\n return { body: 'count' in envelope ? envelope : envelope.data, extra: { ...extra } };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"response-reader.js","sourceRoot":"","sources":["../../../../../src/base/repositories/common/response-reader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAC7B,6GAA6G;aAC7F,8BAAyB,GAAG,OAAO,CAAC;IAEpD,MAAM,CAAC,aAAa,CAAC,KAAc;QACjC,OAAO,CACL,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,MAAM,CAAC,SAAS,CAC1F,CAAC;IACJ,CAAC;IAED,oEAAoE;IACpE,MAAM,CAAC,MAAM,CAAC,KAAc;QAC1B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACvE,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,iBAAiB,CAAC,IAExB;QACC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAExB,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,O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AO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAE1D,IACE,CAAC,QAAQ;YACT,CAAC,kBAAkB,CAAC,aAAa,CAAC,IAAI,CAAC;YACvC,CAAC,kBAAkB,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,EAC7C,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,CAAC;QAClB,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,GAAG,QAAQ,EAAE,GAAG,IAAI,CAAC;QAEpC,OAAO,EAAE,IAAI,EAAE,OAAO,IAAI,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,EAAE,CAAC;IACvF,CAAC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport type { TJsonValue } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { ApplicationError, TResponsedError } from '@venizia/ignis-helpers/core';\n\n/**\n * What an IGNIS server answers - `Content-Range`, the error envelope - read once, here, for every\n * client of that server: the http connector, and a client that reads it without the connector.\n */\nexport class HttpResponseReader {\n /** A content type that names JSON: `application/json`, `application/problem+json`, `application/ld+json`. */\n static readonly JSON_CONTENT_TYPE_PATTERN = /json/i;\n\n static isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n !!value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype\n );\n }\n\n /** An empty string reads as absent, so a fallback still applies. */\n static toText(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n }\n\n /**\n * A `Content-Range` header as the IGNIS server writes it: `records 0-24/137` -> skip 0, total 137;\n * an empty page, `records *\\/137` -> total 137. Anything else, including an absent header or an\n * unknown total, is `undefined`.\n */\n static parseContentRange(opts: {\n header?: string | null;\n }): { skip?: number; total: number } | undefined {\n const { header } = opts;\n\n if (!header) {\n return undefined;\n }\n\n const range = header.match(/(\\d+)\\s*-\\s*(\\d+)\\s*\\/\\s*(\\d+)/);\n\n if (range) {\n return { skip: Number(range[1]), total: Number(range[3]) };\n }\n\n const unsatisfied = header.match(/\\*\\s*\\/\\s*(\\d+)/);\n\n if (unsatisfied) {\n return { total: Number(unsatisfied[1]) };\n }\n\n return undefined;\n }\n\n /**\n * The IGNIS error envelope - `{ message, statusCode, normalized: { text, code, args }, requestId,\n * extra, details }` - read off a parsed response body. A server configured with `error.rootKey`\n * wraps it under that key; pass the same `rootKey` to unwrap it. A body without that key, or with a\n * non-object under it (a proxy's `{ error: 'Bad Gateway' }`), is read as it stands.\n *\n * A body that is not a plain object yields `{}`; any other body yields its known fields, each\n * `undefined` when absent or mistyped. An empty string reads as absent.\n */\n static readErrorEnvelope(opts: { body: unknown; rootKey?: string }): TResponsedError {\n const { body, rootKey } = opts;\n\n const wrapped = rootKey && HttpResponseReader.isPlainObject(body) ? body[rootKey] : undefined;\n const envelope = HttpResponseReader.isPlainObject(wrapped) ? wrapped : body;\n\n if (!HttpResponseReader.isPlainObject(envelope)) {\n return {};\n }\n\n const { message, statusCode, normalized, requestId, extra, details } = envelope;\n const normalizedRecord = HttpResponseReader.isPlainObject(normalized) ? normalized : {};\n const { text, code, args } = normalizedRecord;\n\n return {\n message: HttpResponseReader.toText(message),\n statusCode: typeof statusCode === 'number' ? statusCode : undefined,\n normalized: {\n text: HttpResponseReader.toText(text),\n code: HttpResponseReader.toText(code),\n args: HttpResponseReader.isPlainObject(args) ? { ...args } : undefined,\n },\n requestId: HttpResponseReader.toText(requestId),\n extra: HttpResponseReader.isPlainObject(extra) ? { ...extra } : undefined,\n details: HttpResponseReader.isPlainObject(details) ? { ...details } : undefined,\n };\n }\n\n /** A failed response's envelope. A body that is not JSON yields `{}`, and the status alone still describes it. */\n static async readError(opts: { response: Response; rootKey?: string }): Promise<TResponsedError> {\n let text;\n\n try {\n const result = await opts.response.text();\n text = result;\n // eslint-disable-next-line venizia/no-silent-catch -- an unreadable body is read as no text; the status alone still describes the failure\n } catch {\n text = '';\n }\n\n let body: unknown;\n\n try {\n body = text ? JSON.parse(text) : undefined;\n // eslint-disable-next-line venizia/no-silent-catch -- a body that is not JSON yields `{}`; the status alone still describes the failure\n } catch {\n return {};\n }\n\n return HttpResponseReader.readErrorEnvelope({ body, rootKey: opts.rootKey });\n }\n\n /**\n * A failed response as the error the server threw: its status, code, args and text, and its\n * `extra` with the `requestId` added. `message` is `context` plus the server's text, for logs;\n * `normalized.text` stays the server's, for display - `HTTP <status>` when the server sent none.\n * `cause` is the server's `details.cause` - a 422's per-field issues, `{ path, message, code }`.\n *\n * `requestId` names the request this client made. A relaying server's `extra` carries the id of\n * the request it made upstream: it joins `upstreamRequestIds`, nearest first, at every hop.\n */\n static async toApplicationError(opts: {\n response: Response;\n /** Where it failed, for logs - e.g. `[HttpDataSource][read] 404 | /tickets`. */\n context: string;\n rootKey?: string;\n }): Promise<ApplicationError> {\n const { response, context, rootKey } = opts;\n const server = await HttpResponseReader.readError({ response, rootKey });\n const serverText = server.normalized?.text ?? server.message;\n const displayText = serverText ?? `HTTP ${response.status}`;\n\n const extra: Record<string, unknown> = { ...server.extra };\n\n if (server.requestId) {\n const upstreamRequestId = extra.requestId;\n extra.requestId = server.requestId;\n\n if (upstreamRequestId !== undefined && upstreamRequestId !== server.requestId) {\n const known = Array.isArray(extra.upstreamRequestIds) ? extra.upstreamRequestIds : [];\n extra.upstreamRequestIds = [upstreamRequestId, ...known];\n }\n }\n\n return getError({\n statusCode: response.status,\n message: serverText ? `${context} | ${serverText}` : context,\n messageCode: server.normalized?.code,\n messageArgs: server.normalized?.args,\n extra: Object.keys(extra).length > 0 ? extra : undefined,\n cause: server.details?.cause,\n transform: ({ message }) => ({ ...message, text: displayText }),\n });\n }\n\n /**\n * The body as text: `''` for a 204 or an empty body. `response.json()` throws on those, and each client\n * that reads a response has copied the guard.\n */\n static async readText(opts: { response: Response }): Promise<string> {\n const { response } = opts;\n\n return response.status === HTTP.ResultCodes.RS_2.NoContent ? '' : response.text();\n }\n\n /**\n * The body of a success answer, by what it says it is: `null` for a 204 or an empty body, the parsed\n * value when the content type names JSON (`application/json`, `application/problem+json`), the text itself\n * for any other type (`text/plain`, `text/csv`). A body that claims JSON and is not is a `502` that names\n * `context` (where it happened, e.g. `[Client][read] 200 | /tickets`), its size and its content type; its\n * content stays out of the message, which a relaying server may pass to its own clients.\n */\n static async readBody(opts: { response: Response; context: string }): Promise<TJsonValue> {\n const { response, context } = opts;\n const text = await HttpResponseReader.readText({ response });\n\n if (!text) {\n return null;\n }\n\n if (\n !HttpResponseReader.JSON_CONTENT_TYPE_PATTERN.test(\n response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? '',\n )\n ) {\n return text;\n }\n\n return HttpResponseReader.parseJson({ text, response, context });\n }\n\n /**\n * The body as JSON whatever its content type says, `null` for a 204 or an empty body: for a route that\n * answers JSON under a type a proxy rewrote. Errors as `readBody` does.\n */\n static async readJson(opts: { response: Response; context: string }): Promise<TJsonValue> {\n const { response, context } = opts;\n const text = await HttpResponseReader.readText({ response });\n\n if (!text) {\n return null;\n }\n\n return HttpResponseReader.parseJson({ text, response, context });\n }\n\n private static parseJson(opts: {\n text: string;\n response: Response;\n context: string;\n }): TJsonValue {\n const { text, response, context } = opts;\n\n try {\n return JSON.parse(text);\n } catch {\n const contentType = response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none';\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.BadGateway,\n message: `${context} | The response body is not JSON (${text.length} chars, content-type: ${contentType})`,\n });\n }\n }\n\n /**\n * A body the server marked with `x-response-extra` carries `extra` beside its rows. `body` is what\n * the route answers without extras: the `{ count, data }` envelope when the count was asked for in\n * the body, the rows otherwise. Any other body is returned as it stands - an unmarked object is\n * never unwrapped, so a row that has `data` and `extra` columns of its own is never misread.\n */\n static readExtra(opts: { body: unknown; headers: Pick<Headers, 'has'> }): {\n body: unknown;\n extra?: Record<string, unknown>;\n } {\n const { body, headers } = opts;\n const isMarked = headers.has(HTTP.Headers.RESPONSE_EXTRA);\n\n if (\n !isMarked ||\n !HttpResponseReader.isPlainObject(body) ||\n !HttpResponseReader.isPlainObject(body.extra)\n ) {\n return { body };\n }\n\n const { extra, ...envelope } = body;\n\n return { body: 'count' in envelope ? envelope : envelope.data, extra: { ...extra } };\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { DataSourceRoot } from '../../../datasources/index.js';
|
|
2
2
|
import type { AbstractEntity, IdType } from '../../../models/index.js';
|
|
3
3
|
import type { TByIdFilter, TFields, TFilter, TRow, TWhere } from '@venizia/ignis-filter';
|
|
4
4
|
import type { TNullable } from '@venizia/ignis-helpers/common';
|
|
@@ -9,7 +9,7 @@ import type { TCount, TDataWithRange } from './results.js';
|
|
|
9
9
|
* `getEntitySchema()`/`getConnector()`) stay on the connector's own repository tier.
|
|
10
10
|
*/
|
|
11
11
|
export interface IRepository {
|
|
12
|
-
dataSource:
|
|
12
|
+
dataSource: DataSourceRoot;
|
|
13
13
|
entity: AbstractEntity;
|
|
14
14
|
getEntity(): AbstractEntity;
|
|
15
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contracts.js","sourceRoot":"","sources":["../../../../../../src/base/repositories/common/types/contracts.ts"],"names":[],"mappings":"","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"contracts.js","sourceRoot":"","sources":["../../../../../../src/base/repositories/common/types/contracts.ts"],"names":[],"mappings":"","sourcesContent":["import type { DataSourceRoot } from '@/base/datasources';\nimport type { AbstractEntity, IdType } from '@/base/models';\nimport type { TByIdFilter, TFields, TFilter, TRow, TWhere } from '@venizia/ignis-filter';\nimport type { TNullable } from '@venizia/ignis-helpers/common';\nimport type { IExtraOptions, TFindOneOptions, TFindOptions, TFindRangeOptions } from './options';\nimport type { TCount, TDataWithRange } from './results';\n\n/**\n * Base repository interface shared by every engine - engine-specific accessors (postgres's\n * `getEntitySchema()`/`getConnector()`) stay on the connector's own repository tier.\n */\nexport interface IRepository {\n dataSource: DataSourceRoot;\n entity: AbstractEntity;\n getEntity(): AbstractEntity;\n}\n\n/** Interface for read-only repository operations. `TDataObject` is the row/document shape itself. */\nexport interface IReadableRepository<\n TDataObject extends object = object,\n ExtraOptions extends IExtraOptions = IExtraOptions,\n> extends IRepository {\n count(opts: { where: TWhere<TDataObject>; options?: ExtraOptions }): Promise<TCount>;\n existsWith(opts: { where: TWhere<TDataObject>; options?: ExtraOptions }): Promise<boolean>;\n\n find<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options: TFindRangeOptions<ExtraOptions, TRow<TDataObject, R, F>>;\n }): Promise<TDataWithRange<TRow<TDataObject, R, F>>>;\n\n find<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options?: TFindOptions<ExtraOptions, TRow<TDataObject, R, F>>;\n }): Promise<Array<TRow<TDataObject, R, F>>>;\n\n findOne<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options?: TFindOneOptions<ExtraOptions, TRow<TDataObject, R, F>>;\n }): Promise<TNullable<TRow<TDataObject, R, F>>>;\n\n findById<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n id: IdType;\n filter?: TByIdFilter<TDataObject, F>;\n options?: TFindOneOptions<ExtraOptions, TRow<TDataObject, R, F>>;\n }): Promise<TNullable<TRow<TDataObject, R, F>>>;\n}\n\n/** Interface for create operations. */\nexport interface ICreatableRepository<\n TDataObject extends object = object,\n TPersistObject extends object = TDataObject,\n ExtraOptions extends IExtraOptions = IExtraOptions,\n> extends IRepository {\n create(opts: {\n data: TPersistObject;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n create<R = TDataObject>(opts: {\n data: TPersistObject;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n createAll(opts: {\n data: Array<TPersistObject>;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n createAll<R = TDataObject>(opts: {\n data: Array<TPersistObject>;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: Array<R> }>;\n}\n\n/** Interface for update operations. */\nexport interface IUpdatableRepository<\n TDataObject extends object = object,\n TPersistObject extends object = TDataObject,\n ExtraOptions extends IExtraOptions = IExtraOptions,\n> extends IRepository {\n updateById(opts: {\n id: IdType;\n data: Partial<TPersistObject>;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n updateById<R = TDataObject>(opts: {\n id: IdType;\n data: Partial<TPersistObject>;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n updateBy(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n updateBy<R = TDataObject>(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n}\n\n/** Interface for delete operations. */\nexport interface IDeletableRepository<\n TDataObject extends object = object,\n ExtraOptions extends IExtraOptions = IExtraOptions,\n> extends IRepository {\n deleteById(opts: {\n id: IdType;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n deleteById<R = TDataObject>(opts: {\n id: IdType;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n deleteBy(opts: {\n where: TWhere<TDataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n deleteBy<R = TDataObject>(opts: {\n where: TWhere<TDataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n}\n\n/** Interface for a repository that can undo a soft delete. */\nexport interface IRestorableRepository<\n TDataObject extends object = object,\n ExtraOptions extends IExtraOptions = IExtraOptions,\n> extends IRepository {\n restoreById<R = TDataObject>(opts: {\n id: IdType;\n options?: ExtraOptions & { shouldReturn?: boolean };\n }): Promise<TCount & { data: TNullable<R> }>;\n\n restoreBy<R = TDataObject>(opts: {\n where: TWhere<TDataObject>;\n options?: ExtraOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }>;\n}\n\n/** Interface for full CRUD repository operations - reads plus create, update, and delete. */\nexport interface IPersistableRepository<\n TDataObject extends object = object,\n TPersistObject extends object = TDataObject,\n ExtraOptions extends IExtraOptions = IExtraOptions,\n>\n extends\n IReadableRepository<TDataObject, ExtraOptions>,\n ICreatableRepository<TDataObject, TPersistObject, ExtraOptions>,\n IUpdatableRepository<TDataObject, TPersistObject, ExtraOptions>,\n IDeletableRepository<TDataObject, ExtraOptions> {}\n\n/**\n * Alias for IPersistableRepository - the name both DefaultRelationalRepository and\n * DefaultSearchRepository satisfy.\n */\nexport interface ICrudRepository<\n TDataObject extends object = object,\n TPersistObject extends object = TDataObject,\n ExtraOptions extends IExtraOptions = IExtraOptions,\n> extends IPersistableRepository<TDataObject, TPersistObject, ExtraOptions> {}\n"]}
|
|
@@ -5,8 +5,8 @@ import type { SQL } from 'drizzle-orm';
|
|
|
5
5
|
import type { TLockStrength } from '../constants.js';
|
|
6
6
|
import type { TDataWithRange } from './results.js';
|
|
7
7
|
/** Update data supporting both regular fields and JSON path updates via dot notation. */
|
|
8
|
-
export type TUpdateData<T =
|
|
9
|
-
[jsonPath: string]:
|
|
8
|
+
export type TUpdateData<T = object> = Partial<T> & {
|
|
9
|
+
[jsonPath: string]: unknown;
|
|
10
10
|
};
|
|
11
11
|
/** Options for Drizzle ORM query building, used internally by FilterBuilder. */
|
|
12
12
|
export type TDrizzleQueryOptions = Partial<{
|