@opra/nestjs 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 (68) hide show
  1. package/README.md +1 -0
  2. package/cjs/augmentation/http-controller.augmentation.js +16 -0
  3. package/cjs/index.js +2 -5
  4. package/cjs/interfaces/opra-module-options.interface.js +16 -1
  5. package/cjs/opra-http-core.module.js +52 -0
  6. package/cjs/opra-http.module.js +23 -0
  7. package/cjs/opra-nestjs-adapter.js +138 -0
  8. package/cjs/services/opra-exception-filter.js +14 -13
  9. package/esm/augmentation/http-controller.augmentation.js +16 -0
  10. package/esm/index.js +2 -5
  11. package/esm/interfaces/opra-module-options.interface.js +17 -1
  12. package/esm/opra-http-core.module.js +49 -0
  13. package/esm/opra-http.module.js +20 -0
  14. package/esm/opra-nestjs-adapter.js +133 -0
  15. package/esm/services/opra-exception-filter.js +13 -13
  16. package/package.json +12 -11
  17. package/types/augmentation/http-controller.augmentation.d.ts +0 -0
  18. package/types/index.d.ts +2 -5
  19. package/types/interfaces/opra-module-options.interface.d.ts +0 -25
  20. package/types/opra-http-core.module.d.ts +9 -0
  21. package/types/opra-http.module.d.ts +16 -0
  22. package/types/opra-nestjs-adapter.d.ts +10 -0
  23. package/types/services/opra-exception-filter.d.ts +6 -2
  24. package/cjs/augmentation/common-decorator.augmentation.js +0 -40
  25. package/cjs/constants.js +0 -9
  26. package/cjs/decorators/context.decorator.js +0 -10
  27. package/cjs/enums/handler-paramtype.enum.js +0 -9
  28. package/cjs/factories/opra-api.factory.js +0 -200
  29. package/cjs/factories/params.factory.js +0 -23
  30. package/cjs/opra-core.module.js +0 -140
  31. package/cjs/opra-module-ref.js +0 -16
  32. package/cjs/opra.module.js +0 -25
  33. package/cjs/services/nest-explorer.js +0 -38
  34. package/cjs/services/opra-api-loader.js +0 -85
  35. package/cjs/types.js +0 -2
  36. package/cjs/utils/class.utils.js +0 -25
  37. package/cjs/utils/function.utils.js +0 -37
  38. package/cjs/utils/param.utils.js +0 -24
  39. package/esm/augmentation/common-decorator.augmentation.js +0 -38
  40. package/esm/constants.js +0 -6
  41. package/esm/decorators/context.decorator.js +0 -7
  42. package/esm/enums/handler-paramtype.enum.js +0 -6
  43. package/esm/factories/opra-api.factory.js +0 -197
  44. package/esm/factories/params.factory.js +0 -19
  45. package/esm/opra-core.module.js +0 -137
  46. package/esm/opra-module-ref.js +0 -12
  47. package/esm/opra.module.js +0 -22
  48. package/esm/services/nest-explorer.js +0 -34
  49. package/esm/services/opra-api-loader.js +0 -81
  50. package/esm/types.js +0 -1
  51. package/esm/utils/class.utils.js +0 -19
  52. package/esm/utils/function.utils.js +0 -33
  53. package/esm/utils/param.utils.js +0 -20
  54. package/types/augmentation/common-decorator.augmentation.d.ts +0 -1
  55. package/types/constants.d.ts +0 -6
  56. package/types/decorators/context.decorator.d.ts +0 -5
  57. package/types/enums/handler-paramtype.enum.d.ts +0 -5
  58. package/types/factories/opra-api.factory.d.ts +0 -15
  59. package/types/factories/params.factory.d.ts +0 -4
  60. package/types/opra-core.module.d.ts +0 -17
  61. package/types/opra-module-ref.d.ts +0 -11
  62. package/types/opra.module.d.ts +0 -6
  63. package/types/services/nest-explorer.d.ts +0 -8
  64. package/types/services/opra-api-loader.d.ts +0 -19
  65. package/types/types.d.ts +0 -2
  66. package/types/utils/class.utils.d.ts +0 -4
  67. package/types/utils/function.utils.d.ts +0 -1
  68. package/types/utils/param.utils.d.ts +0 -8
@@ -1,85 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OpraApiLoader = void 0;
4
- const tslib_1 = require("tslib");
5
- const common_1 = require("@nestjs/common");
6
- const core_1 = require("@nestjs/core");
7
- const common_2 = require("@opra/common");
8
- const core_2 = require("@opra/core");
9
- const constants_js_1 = require("../constants.js");
10
- const opra_api_factory_js_1 = require("../factories/opra-api.factory.js");
11
- const opra_module_ref_js_1 = require("../opra-module-ref.js");
12
- class OpraApiLoader {
13
- constructor() {
14
- this.logger = new common_1.Logger(OpraApiLoader.name, { timestamp: true });
15
- this.opraModuleRef = new opra_module_ref_js_1.OpraModuleRef();
16
- }
17
- async initialize(rootModule) {
18
- const httpAdapter = this.httpAdapterHost?.httpAdapter;
19
- const globalPrefix = this.applicationConfig.getGlobalPrefix();
20
- const platformName = httpAdapter.getType();
21
- const moduleOptions = this.options;
22
- this.opraModuleRef[constants_js_1.kOptions] = this.options;
23
- let prefixPath = new common_2.OpraURLPath((moduleOptions.useGlobalPrefix !== false ? globalPrefix : ''));
24
- if (moduleOptions.basePath)
25
- prefixPath = prefixPath.join(moduleOptions.basePath);
26
- const name = moduleOptions.document?.info?.title || 'untitled service';
27
- const options = {
28
- ...moduleOptions,
29
- basePath: prefixPath.toString()
30
- };
31
- try {
32
- const apiDocument = await this.opraFactory.generateService(rootModule, 'http', options.document);
33
- if (!Object.keys(apiDocument.root).length) {
34
- this.logger.warn(`No Sources found (${name})`);
35
- return;
36
- }
37
- if (platformName === 'express') {
38
- this.opraModuleRef[constants_js_1.kAdapter] = await this.registerExpress(apiDocument, options);
39
- // else if (platformName === 'fastify')
40
- // await this.registerFastify();
41
- }
42
- else { // noinspection ExceptionCaughtLocallyJS
43
- throw new Error(`No support for current HttpAdapter: ${platformName}`);
44
- }
45
- this.logger.log(`Mapped {${prefixPath.toString() || '/'}} to "${name}" service`);
46
- }
47
- catch (e) {
48
- this.logger.error(e);
49
- throw e;
50
- }
51
- }
52
- async stop() {
53
- //
54
- }
55
- async registerExpress(apiDocument, moduleOptions) {
56
- const httpAdapter = this.httpAdapterHost.httpAdapter;
57
- /* istanbul ignore next */
58
- if (!httpAdapter)
59
- throw new Error('HttpAdapterHost is not initialized');
60
- const app = httpAdapter.getInstance();
61
- const logger = moduleOptions.logger ||
62
- (process.env.NODE_ENV === 'test' ? undefined : new common_1.Logger(apiDocument.info.title));
63
- return await core_2.ExpressAdapter.create(app, apiDocument, {
64
- ...moduleOptions,
65
- logger,
66
- });
67
- }
68
- }
69
- exports.OpraApiLoader = OpraApiLoader;
70
- tslib_1.__decorate([
71
- (0, common_1.Inject)(),
72
- tslib_1.__metadata("design:type", core_1.HttpAdapterHost)
73
- ], OpraApiLoader.prototype, "httpAdapterHost", void 0);
74
- tslib_1.__decorate([
75
- (0, common_1.Inject)(),
76
- tslib_1.__metadata("design:type", core_1.ApplicationConfig)
77
- ], OpraApiLoader.prototype, "applicationConfig", void 0);
78
- tslib_1.__decorate([
79
- (0, common_1.Inject)(),
80
- tslib_1.__metadata("design:type", opra_api_factory_js_1.OpraApiFactory)
81
- ], OpraApiLoader.prototype, "opraFactory", void 0);
82
- tslib_1.__decorate([
83
- (0, common_1.Inject)(constants_js_1.OPRA_MODULE_OPTIONS),
84
- tslib_1.__metadata("design:type", Object)
85
- ], OpraApiLoader.prototype, "options", void 0);
package/cjs/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getClassName = exports.getClassOrUndefined = exports.isConstructor = void 0;
4
- const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5
- function isConstructor(obj) {
6
- return typeof obj === 'function' &&
7
- !!(obj.prototype && obj.prototype.constructor);
8
- }
9
- exports.isConstructor = isConstructor;
10
- function getClassOrUndefined(typeOrFunc) {
11
- return isConstructor(typeOrFunc)
12
- ? typeOrFunc
13
- : (0, shared_utils_1.isFunction)(typeOrFunc)
14
- ? typeOrFunc()
15
- : undefined;
16
- }
17
- exports.getClassOrUndefined = getClassOrUndefined;
18
- function getClassName(nameOrType) {
19
- if ((0, shared_utils_1.isString)(nameOrType)) {
20
- return nameOrType;
21
- }
22
- const classOrUndefined = getClassOrUndefined(nameOrType);
23
- return classOrUndefined && classOrUndefined.name;
24
- }
25
- exports.getClassName = getClassName;
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getNumberOfArguments = void 0;
4
- const fast_tokenizer_1 = require("fast-tokenizer");
5
- function getNumberOfArguments(fn) {
6
- const functionAsString = fn.toString();
7
- const tokenizer = (0, fast_tokenizer_1.tokenize)(functionAsString, {
8
- // keepBrackets: true,
9
- keepDelimiters: true,
10
- keepQuotes: true,
11
- brackets: {}
12
- });
13
- let k = 0;
14
- let s = '';
15
- for (const token of tokenizer) {
16
- if (token.startsWith('(')) {
17
- s += token.substring(1);
18
- k++;
19
- }
20
- else if (token.startsWith(')')) {
21
- if (k === 1)
22
- break;
23
- }
24
- else if (k)
25
- s += token;
26
- }
27
- const x = (0, fast_tokenizer_1.splitString)(s, {
28
- brackets: {
29
- '{': '}',
30
- '(': ')',
31
- '[': ']',
32
- '/*': '*/'
33
- }, delimiters: ','
34
- });
35
- return x.length > 1 ? x.length : (x[0] ? 1 : 0);
36
- }
37
- exports.getNumberOfArguments = getNumberOfArguments;
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createOpraParamDecorator = void 0;
4
- require("reflect-metadata");
5
- const constants_js_1 = require("../constants.js");
6
- function assignMetadata(args, paramType, index, data, ...pipes) {
7
- return {
8
- ...args,
9
- [`${paramType}:${index}`]: {
10
- index,
11
- data,
12
- pipes,
13
- },
14
- };
15
- }
16
- function createOpraParamDecorator(paramType) {
17
- return (target, key, index) => {
18
- if (!key)
19
- return;
20
- const args = Reflect.getMetadata(constants_js_1.PARAM_ARGS_METADATA, target.constructor, key) || {};
21
- Reflect.defineMetadata(constants_js_1.PARAM_ARGS_METADATA, assignMetadata(args, paramType, index), target.constructor, key);
22
- };
23
- }
24
- exports.createOpraParamDecorator = createOpraParamDecorator;
@@ -1,38 +0,0 @@
1
- import { Injectable } from '@nestjs/common';
2
- import { Collection, DECORATOR, Singleton, Storage } from '@opra/common';
3
- /*
4
- Overrides Collection decorator function to call NestJS's Injectable() when Collection decorator called
5
- */
6
- const oldCollectionDecorator = Collection[DECORATOR];
7
- Collection[DECORATOR] = function CollectionDecorator(...args) {
8
- const collectionDecorator = oldCollectionDecorator(...args);
9
- const injectableDecorator = Injectable();
10
- return (target) => {
11
- collectionDecorator(target);
12
- injectableDecorator(target);
13
- };
14
- };
15
- /*
16
- Overrides Singleton decorator function to call NestJS's Injectable() when Singleton decorator called
17
- */
18
- const oldSingletonDecorator = Singleton[DECORATOR];
19
- Singleton[DECORATOR] = function SingletonDecorator(...args) {
20
- const singletonDecorator = oldSingletonDecorator(...args);
21
- const injectableDecorator = Injectable();
22
- return (target) => {
23
- singletonDecorator(target);
24
- injectableDecorator(target);
25
- };
26
- };
27
- /*
28
- Overrides Singleton decorator function to call NestJS's Injectable() when Singleton decorator called
29
- */
30
- const oldStorageDecorator = Storage[DECORATOR];
31
- Storage[DECORATOR] = function StorageDecorator(...args) {
32
- const storageDecorator = oldStorageDecorator(...args);
33
- const injectableDecorator = Injectable();
34
- return (target) => {
35
- storageDecorator(target);
36
- injectableDecorator(target);
37
- };
38
- };
package/esm/constants.js DELETED
@@ -1,6 +0,0 @@
1
- export const OPRA_MODULE_OPTIONS = 'opra:module_options';
2
- export const OPRA_MODULE_ID = 'opra:module_id';
3
- export const OPRA_INITIALIZER = 'opra_initializer';
4
- export const kOptions = Symbol('kOptions');
5
- export const kAdapter = Symbol('kAdapter');
6
- export const PARAM_ARGS_METADATA = '__routeArguments__';
@@ -1,7 +0,0 @@
1
- import { HandlerParamType } from '../enums/handler-paramtype.enum.js';
2
- import { createOpraParamDecorator } from '../utils/param.utils.js';
3
- /**
4
- * Handler method parameter decorator. Populates the decorated
5
- * parameter with the value of `RequestContext`.
6
- */
7
- export const Context = createOpraParamDecorator(HandlerParamType.CONTEXT);
@@ -1,6 +0,0 @@
1
- export var HandlerParamType;
2
- (function (HandlerParamType) {
3
- HandlerParamType[HandlerParamType["CONTEXT"] = 0] = "CONTEXT";
4
- HandlerParamType[HandlerParamType["REQUEST"] = 1] = "REQUEST";
5
- HandlerParamType[HandlerParamType["RESPONSE"] = 2] = "RESPONSE";
6
- })(HandlerParamType || (HandlerParamType = {}));
@@ -1,197 +0,0 @@
1
- import { __decorate, __metadata } from "tslib";
2
- import head from 'lodash.head';
3
- import { Inject, Injectable } from '@nestjs/common';
4
- import { ContextIdFactory, createContextId, ModulesContainer, REQUEST } from '@nestjs/core';
5
- import { ExternalContextCreator } from '@nestjs/core/helpers/external-context-creator';
6
- import { Injector } from '@nestjs/core/injector/injector';
7
- import { InternalCoreModule } from '@nestjs/core/injector/internal-core-module';
8
- import { REQUEST_CONTEXT_ID } from '@nestjs/core/router/request/request-constants';
9
- import { ApiDocumentFactory, OpraSchema, RESOURCE_METADATA } from '@opra/common';
10
- import { PARAM_ARGS_METADATA } from '../constants.js';
11
- import { HandlerParamType } from '../enums/handler-paramtype.enum.js';
12
- import { NestExplorer } from '../services/nest-explorer.js';
13
- import { getNumberOfArguments } from '../utils/function.utils.js';
14
- import { OpraParamsFactory } from './params.factory.js';
15
- const noOpFunction = () => void 0;
16
- let OpraApiFactory = class OpraApiFactory {
17
- constructor() {
18
- this.paramsFactory = new OpraParamsFactory();
19
- this.injector = new Injector();
20
- }
21
- async generateService(rootModule, contextType, apiSchema) {
22
- const info = { ...apiSchema?.info };
23
- info.title = info.title || 'Untitled service';
24
- info.version = info.version || '1';
25
- const root = {
26
- resources: []
27
- };
28
- const apiInit = {
29
- version: OpraSchema.SpecVersion,
30
- ...apiSchema,
31
- info,
32
- types: apiSchema?.types || [],
33
- root
34
- };
35
- /*
36
- * Walk through modules and add Resource instances to the api schema
37
- */
38
- this.explorerService.exploreResources(rootModule, (wrapper, modulePath) => {
39
- const instance = wrapper.instance;
40
- const ctor = instance.constructor;
41
- const metadata = Reflect.getMetadata(RESOURCE_METADATA, ctor);
42
- let node = root;
43
- modulePath.forEach(m => {
44
- const mt = Reflect.getMetadata(RESOURCE_METADATA, m._metatype);
45
- if (mt) {
46
- let n = node.resources.find(x => x.controller === m.instance);
47
- if (!n) {
48
- n = {
49
- ...mt,
50
- kind: 'Container',
51
- resources: [...(mt.resources || [])],
52
- controller: m.instance
53
- };
54
- node.resources.push(n);
55
- }
56
- node = n;
57
- }
58
- });
59
- // Do not add Modules decorated with @Container
60
- if (wrapper.metatype !== wrapper.host?.metatype)
61
- node.resources.push(instance);
62
- /* Wrap operation and action functions */
63
- const isRequestScoped = !wrapper.isDependencyTreeStatic();
64
- const methodNames = [...Object.keys(metadata.operations || []), ...Object.keys(metadata.actions || [])];
65
- for (const methodName of methodNames) {
66
- const endpointFunction = instance[methodName];
67
- const nestHandlerName = methodName + '_nestjs';
68
- // Skip patch if controller do not have function for endpoint or already patched before
69
- if (typeof endpointFunction !== 'function')
70
- continue;
71
- // NestJs requires calling handler function in different order than Opra.
72
- // In NestJS, handler functions must be called with these parameters (req, res, next)
73
- // In Opra, handler functions must be called with these parameters (context)
74
- // To work handlers properly we create new handlers that will work as a proxy to wrap parameters
75
- // Opra request (context) -> Nest (req, res, next, context: QueryRequestContext) -> Opra response (context)
76
- const paramArgsMetadata = Reflect.getMetadata(PARAM_ARGS_METADATA, instance.constructor, methodName);
77
- const hasParamsArgs = !!paramArgsMetadata;
78
- const patchedFn = instance[nestHandlerName] = function (...args) {
79
- if (hasParamsArgs)
80
- return endpointFunction.apply(this, args);
81
- return endpointFunction.call(this, args[3]);
82
- };
83
- if (paramArgsMetadata)
84
- Reflect.defineMetadata(PARAM_ARGS_METADATA, paramArgsMetadata, instance.constructor, nestHandlerName);
85
- // Copy all metadata from old Function to new one
86
- Reflect.getMetadataKeys(endpointFunction).forEach(k => {
87
- const m = Reflect.getMetadata(k, endpointFunction);
88
- Reflect.defineMetadata(k, m, patchedFn);
89
- });
90
- this._createContextCallback(instance, wrapper, rootModule, methodName, isRequestScoped, contextType);
91
- }
92
- });
93
- // Create api document
94
- return ApiDocumentFactory.createDocument(apiInit);
95
- }
96
- _createHandler(callback) {
97
- return function (ctx) {
98
- switch (ctx.protocol) {
99
- case 'http':
100
- const httpContext = ctx.switchToHttp();
101
- return callback(httpContext.incoming, httpContext.outgoing, noOpFunction, ctx);
102
- default:
103
- throw new Error(`"${ctx.protocol}" context type is not implemented yet`);
104
- }
105
- };
106
- }
107
- _createContextCallback(instance, wrapper, moduleRef, methodName, isRequestScoped, contextType, options) {
108
- const paramsFactory = this.paramsFactory;
109
- const nestHandlerName = methodName + '_nestjs';
110
- const callback = isRequestScoped
111
- ? async (...args) => {
112
- const opraContext = paramsFactory.exchangeKeyForValue(HandlerParamType.CONTEXT, undefined, args);
113
- const contextId = this.getContextId(opraContext);
114
- this.registerContextProvider(opraContext, contextId);
115
- const contextInstance = await this.injector.loadPerContext(instance, moduleRef, moduleRef.providers, contextId);
116
- const contextCallback = this.externalContextCreator.create(contextInstance, contextInstance[methodName], nestHandlerName, PARAM_ARGS_METADATA, paramsFactory, contextId, wrapper.id, options, opraContext.protocol);
117
- contextInstance[methodName] = this._createHandler(contextCallback);
118
- return contextCallback(...args);
119
- }
120
- : this.externalContextCreator.create(instance, instance[nestHandlerName], nestHandlerName, PARAM_ARGS_METADATA, paramsFactory, undefined, undefined, options, contextType);
121
- instance[methodName] = this._createHandler(callback);
122
- return callback;
123
- }
124
- // noinspection JSMethodCanBeStatic
125
- getContextId(gqlContext) {
126
- const numberOfArguments = getNumberOfArguments(ContextIdFactory.getByRequest);
127
- if (numberOfArguments === 2) {
128
- // @ts-ignore
129
- const contextId = ContextIdFactory.getByRequest(gqlContext, ['req']);
130
- if (!gqlContext[REQUEST_CONTEXT_ID]) {
131
- Object.defineProperty(gqlContext, REQUEST_CONTEXT_ID, {
132
- value: contextId,
133
- enumerable: false,
134
- configurable: false,
135
- writable: false,
136
- });
137
- }
138
- return contextId;
139
- }
140
- else {
141
- // TODO remove in the next version (backward-compatibility layer)
142
- // Left for backward compatibility purposes
143
- let contextId;
144
- if (gqlContext && gqlContext[REQUEST_CONTEXT_ID]) {
145
- contextId = gqlContext[REQUEST_CONTEXT_ID];
146
- }
147
- else if (gqlContext &&
148
- gqlContext.req &&
149
- gqlContext.req[REQUEST_CONTEXT_ID]) {
150
- contextId = gqlContext.req[REQUEST_CONTEXT_ID];
151
- }
152
- else {
153
- contextId = createContextId();
154
- Object.defineProperty(gqlContext, REQUEST_CONTEXT_ID, {
155
- value: contextId,
156
- enumerable: false,
157
- configurable: false,
158
- writable: false,
159
- });
160
- }
161
- return contextId;
162
- }
163
- }
164
- registerContextProvider(request, contextId) {
165
- const coreModuleArray = [...this.modulesContainer.entries()]
166
- .filter(
167
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
168
- ([key, { metatype }]) => metatype && metatype.name === InternalCoreModule.name)
169
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
170
- .map(([key, value]) => value);
171
- const coreModuleRef = head(coreModuleArray);
172
- if (!coreModuleRef) {
173
- return;
174
- }
175
- const wrapper = coreModuleRef.getProviderByKey(REQUEST);
176
- wrapper.setInstanceByContextId(contextId, {
177
- instance: request,
178
- isResolved: true,
179
- });
180
- }
181
- };
182
- __decorate([
183
- Inject(),
184
- __metadata("design:type", ModulesContainer)
185
- ], OpraApiFactory.prototype, "modulesContainer", void 0);
186
- __decorate([
187
- Inject(),
188
- __metadata("design:type", ExternalContextCreator)
189
- ], OpraApiFactory.prototype, "externalContextCreator", void 0);
190
- __decorate([
191
- Inject(),
192
- __metadata("design:type", NestExplorer)
193
- ], OpraApiFactory.prototype, "explorerService", void 0);
194
- OpraApiFactory = __decorate([
195
- Injectable()
196
- ], OpraApiFactory);
197
- export { OpraApiFactory };
@@ -1,19 +0,0 @@
1
- import { HandlerParamType } from '../enums/handler-paramtype.enum.js';
2
- export class OpraParamsFactory {
3
- exchangeKeyForValue(type, data, args) {
4
- if (!args) {
5
- return null;
6
- }
7
- args = Array.isArray(args) ? args : [];
8
- switch (type) {
9
- case HandlerParamType.CONTEXT:
10
- return args[3];
11
- case HandlerParamType.REQUEST:
12
- return args[3].request;
13
- case HandlerParamType.RESPONSE:
14
- return args[3].response;
15
- default:
16
- return null;
17
- }
18
- }
19
- }
@@ -1,137 +0,0 @@
1
- var OpraCoreModule_1;
2
- import { __decorate, __metadata, __param } from "tslib";
3
- import * as crypto from 'crypto';
4
- import { Global, Inject, Module } from '@nestjs/common';
5
- import { HttpAdapterHost, ModulesContainer } from '@nestjs/core';
6
- import { MetadataScanner } from '@nestjs/core/metadata-scanner';
7
- import { OPRA_INITIALIZER, OPRA_MODULE_ID, OPRA_MODULE_OPTIONS } from './constants.js';
8
- import { OpraApiFactory } from './factories/opra-api.factory.js';
9
- import { OpraModuleRef } from './opra-module-ref.js';
10
- import { NestExplorer } from './services/nest-explorer.js';
11
- import { OpraApiLoader } from './services/opra-api-loader.js';
12
- let OpraCoreModule = OpraCoreModule_1 = class OpraCoreModule {
13
- constructor(httpAdapterHost, modulesContainer, options, apiLoader) {
14
- this.httpAdapterHost = httpAdapterHost;
15
- this.modulesContainer = modulesContainer;
16
- this.options = options;
17
- this.apiLoader = apiLoader;
18
- }
19
- static forRoot(options) {
20
- const providers = [
21
- ...(options.providers || []),
22
- {
23
- provide: OPRA_MODULE_OPTIONS,
24
- useValue: options,
25
- },
26
- {
27
- provide: OPRA_INITIALIZER,
28
- useClass: OpraApiLoader
29
- },
30
- {
31
- provide: options.id || OpraModuleRef,
32
- inject: [OPRA_INITIALIZER],
33
- useFactory: (apiLoader) => {
34
- return apiLoader.opraModuleRef;
35
- }
36
- }
37
- ];
38
- return {
39
- module: OpraCoreModule_1,
40
- imports: [...(options.imports || [])],
41
- exports: [...(options.exports || [])],
42
- providers
43
- };
44
- }
45
- static forRootAsync(asyncOptions) {
46
- return {
47
- module: OpraCoreModule_1,
48
- imports: [...(asyncOptions.imports || [])],
49
- providers: [
50
- ...(asyncOptions.providers || []),
51
- {
52
- provide: OPRA_MODULE_ID,
53
- useValue: crypto.randomUUID()
54
- },
55
- {
56
- provide: OPRA_INITIALIZER,
57
- useClass: OpraApiLoader
58
- },
59
- {
60
- provide: asyncOptions.id || OpraModuleRef,
61
- inject: [OPRA_INITIALIZER],
62
- useFactory: (apiLoader) => {
63
- return apiLoader.opraModuleRef;
64
- }
65
- },
66
- ...this.createAsyncProviders(asyncOptions)
67
- ]
68
- };
69
- }
70
- static createAsyncProviders(asyncOptions) {
71
- if (asyncOptions.useExisting || asyncOptions.useFactory)
72
- return [this.createAsyncOptionsProvider(asyncOptions)];
73
- if (asyncOptions.useClass)
74
- return [
75
- this.createAsyncOptionsProvider(asyncOptions),
76
- {
77
- provide: asyncOptions.useClass,
78
- useClass: asyncOptions.useClass
79
- }
80
- ];
81
- throw new Error('Invalid configuration. Must provide useFactory, useClass or useExisting');
82
- }
83
- static createAsyncOptionsProvider(asyncOptions) {
84
- if (asyncOptions.useFactory) {
85
- return {
86
- provide: OPRA_MODULE_OPTIONS,
87
- useFactory: asyncOptions.useFactory,
88
- inject: asyncOptions.inject || []
89
- };
90
- }
91
- const useClass = asyncOptions.useClass || asyncOptions.useExisting;
92
- if (useClass) {
93
- return {
94
- provide: OPRA_MODULE_OPTIONS,
95
- useFactory: (optionsFactory) => optionsFactory.createOptions(),
96
- inject: [useClass]
97
- };
98
- }
99
- throw new Error('Invalid configuration. Must provide useFactory, useClass or useExisting');
100
- }
101
- async onModuleInit() {
102
- const httpAdapter = this.httpAdapterHost?.httpAdapter;
103
- if (!httpAdapter)
104
- return;
105
- const opraModule = (() => {
106
- for (const m of this.modulesContainer.values()) {
107
- for (const imp of m.imports.values()) {
108
- for (const prv of imp.providers.values())
109
- if (prv.instance === this) {
110
- return imp;
111
- }
112
- }
113
- }
114
- })();
115
- if (opraModule) {
116
- await this.apiLoader.initialize(opraModule);
117
- }
118
- }
119
- async onModuleDestroy() {
120
- await this.apiLoader.stop();
121
- }
122
- };
123
- OpraCoreModule = OpraCoreModule_1 = __decorate([
124
- Module({
125
- providers: [
126
- OpraApiFactory,
127
- MetadataScanner,
128
- NestExplorer
129
- ]
130
- }),
131
- Global(),
132
- __param(2, Inject(OPRA_MODULE_OPTIONS)),
133
- __param(3, Inject(OPRA_INITIALIZER)),
134
- __metadata("design:paramtypes", [HttpAdapterHost,
135
- ModulesContainer, Object, OpraApiLoader])
136
- ], OpraCoreModule);
137
- export { OpraCoreModule };
@@ -1,12 +0,0 @@
1
- import { kAdapter, kOptions } from './constants.js';
2
- export class OpraModuleRef {
3
- get adapter() {
4
- return this[kAdapter];
5
- }
6
- get api() {
7
- return this[kAdapter].api;
8
- }
9
- get options() {
10
- return this[kOptions];
11
- }
12
- }
@@ -1,22 +0,0 @@
1
- var OpraModule_1;
2
- import { __decorate } from "tslib";
3
- import { Module } from '@nestjs/common';
4
- import { OpraCoreModule } from './opra-core.module.js';
5
- let OpraModule = OpraModule_1 = class OpraModule {
6
- static forRoot(options) {
7
- return {
8
- module: OpraModule_1,
9
- imports: [OpraCoreModule.forRoot(options)]
10
- };
11
- }
12
- static forRootAsync(asyncOptions) {
13
- return {
14
- module: OpraModule_1,
15
- imports: [OpraCoreModule.forRootAsync(asyncOptions)]
16
- };
17
- }
18
- };
19
- OpraModule = OpraModule_1 = __decorate([
20
- Module({})
21
- ], OpraModule);
22
- export { OpraModule };
@@ -1,34 +0,0 @@
1
- import { OpraSchema, RESOURCE_METADATA } from '@opra/common';
2
- export class NestExplorer {
3
- exploreProviders(rootModule, callback) {
4
- const modules = new Set();
5
- const tree = [];
6
- const scanModules = (m) => {
7
- if (modules.has(m))
8
- return;
9
- modules.add(m);
10
- tree.push(m);
11
- for (const mm of m.imports.values()) {
12
- scanModules(mm);
13
- }
14
- for (const wrapper of m.providers.values()) {
15
- callback(wrapper, tree);
16
- if (wrapper.host)
17
- scanModules(wrapper.host);
18
- }
19
- tree.pop();
20
- };
21
- scanModules(rootModule);
22
- }
23
- exploreResources(rootModule, callback) {
24
- this.exploreProviders(rootModule, (wrapper, tree) => {
25
- if (wrapper.instance
26
- && typeof wrapper.instance === 'object'
27
- && wrapper.instance.constructor
28
- && OpraSchema.isResource(Reflect.getMetadata(RESOURCE_METADATA, wrapper.instance.constructor))) {
29
- callback(wrapper, tree);
30
- }
31
- return false;
32
- });
33
- }
34
- }