@opra/nestjs 1.0.0-alpha.3 → 1.0.0-alpha.30

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.
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OPRA_HTTP_MODULE_OPTIONS = exports.IS_PUBLIC_KEY = void 0;
4
+ exports.IS_PUBLIC_KEY = 'opra:isPublic';
5
+ exports.OPRA_HTTP_MODULE_OPTIONS = 'OPRA_HTTP_MODULE_OPTIONS';
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Public = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const constants_js_1 = require("../constants.js");
6
+ const Public = () => (0, common_1.SetMetadata)(constants_js_1.IS_PUBLIC_KEY, true);
7
+ exports.Public = Public;
package/cjs/index.js CHANGED
@@ -3,5 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  require("reflect-metadata");
5
5
  require("./augmentation/nestjs.augmentation.js");
6
+ tslib_1.__exportStar(require("./constants.js"), exports);
7
+ tslib_1.__exportStar(require("./decorators/public.decorator.js"), exports);
6
8
  tslib_1.__exportStar(require("./opra-http.module.js"), exports);
7
9
  tslib_1.__exportStar(require("./opra-nestjs-adapter.js"), exports);
@@ -3,40 +3,70 @@ var OpraHttpCoreModule_1;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.OpraHttpCoreModule = void 0;
5
5
  const tslib_1 = require("tslib");
6
- const ts_gems_1 = require("ts-gems");
7
6
  const common_1 = require("@nestjs/common");
7
+ const core_1 = require("@nestjs/core");
8
8
  const common_2 = require("@opra/common");
9
+ const ts_gems_1 = require("ts-gems");
10
+ const constants_1 = require("./constants");
9
11
  const opra_nestjs_adapter_js_1 = require("./opra-nestjs-adapter.js");
12
+ const opra_exception_filter_1 = require("./services/opra-exception-filter");
13
+ const opra_middleware_js_1 = require("./services/opra-middleware.js");
10
14
  let OpraHttpCoreModule = OpraHttpCoreModule_1 = class OpraHttpCoreModule {
11
15
  constructor(opraAdapter) {
12
16
  this.opraAdapter = opraAdapter;
13
17
  }
14
- static forRoot(options) {
15
- const opraAdapter = new opra_nestjs_adapter_js_1.OpraNestAdapter(options);
16
- const token = options?.id || opra_nestjs_adapter_js_1.OpraNestAdapter;
18
+ configure(consumer) {
19
+ consumer.apply(opra_middleware_js_1.OpraMiddleware).forRoutes({
20
+ path: '*',
21
+ method: common_1.RequestMethod.ALL,
22
+ });
23
+ }
24
+ static forRoot(init, options) {
25
+ const opraAdapter = new opra_nestjs_adapter_js_1.OpraNestAdapter(init, options);
26
+ const token = init?.id || opra_nestjs_adapter_js_1.OpraNestAdapter;
17
27
  const providers = [
18
- ...(options?.providers || []),
28
+ ...(init?.providers || []),
29
+ {
30
+ provide: constants_1.OPRA_HTTP_MODULE_OPTIONS,
31
+ useValue: { ...options },
32
+ },
19
33
  {
20
34
  provide: opra_nestjs_adapter_js_1.OpraNestAdapter,
21
- useFactory: async () => {
35
+ inject: [core_1.ModuleRef],
36
+ useFactory: async (moduleRef) => {
22
37
  (0, ts_gems_1.asMutable)(opraAdapter).document = await common_2.ApiDocumentFactory.createDocument({
23
- ...options,
24
- api: { protocol: 'http', name: options.name, controllers: opraAdapter.controllers },
38
+ ...init,
39
+ api: { protocol: 'http', name: init.name, controllers: init.controllers },
40
+ });
41
+ opraAdapter.interceptors.map(x => {
42
+ if ((0, common_2.isConstructor)(x)) {
43
+ return (ctx, next) => {
44
+ const interceptor = moduleRef.get(x);
45
+ if (typeof interceptor.intercept === 'function')
46
+ return interceptor.intercept(ctx, next());
47
+ };
48
+ }
49
+ return x;
25
50
  });
26
51
  return opraAdapter;
27
52
  },
28
53
  },
54
+ {
55
+ provide: core_1.APP_FILTER,
56
+ useClass: opra_exception_filter_1.OpraExceptionFilter,
57
+ },
29
58
  ];
30
- if (token !== opra_nestjs_adapter_js_1.OpraNestAdapter)
59
+ if (token !== opra_nestjs_adapter_js_1.OpraNestAdapter) {
31
60
  providers.push({
32
61
  provide: token,
33
62
  useValue: opraAdapter,
34
63
  });
64
+ }
35
65
  return {
36
66
  module: OpraHttpCoreModule_1,
37
- controllers: opraAdapter.controllers,
38
- imports: [...(options?.imports || [])],
39
- exports: [...(options?.exports || []), token],
67
+ controllers: opraAdapter.nestControllers,
68
+ imports: [...(init?.imports || [])],
69
+ exports: [...(init?.exports || []), token],
40
70
  providers,
41
71
  };
42
72
  }
@@ -8,12 +8,13 @@ const opra_http_core_module_js_1 = require("./opra-http-core.module.js");
8
8
  let OpraHttpModule = OpraHttpModule_1 = class OpraHttpModule {
9
9
  /**
10
10
  *
11
+ * @param init
11
12
  * @param options
12
13
  */
13
- static forRoot(options) {
14
+ static forRoot(init, options) {
14
15
  return {
15
16
  module: OpraHttpModule_1,
16
- imports: [opra_http_core_module_js_1.OpraHttpCoreModule.forRoot(options)],
17
+ imports: [opra_http_core_module_js_1.OpraHttpCoreModule.forRoot(init, options)],
17
18
  };
18
19
  }
19
20
  };
@@ -1,95 +1,122 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OpraNestAdapter = exports.kHandler = void 0;
3
+ exports.OpraNestAdapter = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const path_1 = tslib_1.__importDefault(require("path"));
6
5
  const common_1 = require("@nestjs/common");
6
+ const constants_1 = require("@nestjs/common/constants");
7
7
  const common_2 = require("@opra/common");
8
8
  const core_1 = require("@opra/core");
9
- const opra_exception_filter_js_1 = require("./services/opra-exception-filter.js");
10
- exports.kHandler = Symbol.for('kHandler');
9
+ const path_1 = tslib_1.__importDefault(require("path"));
10
+ const ts_gems_1 = require("ts-gems");
11
+ const public_decorator_js_1 = require("./decorators/public.decorator.js");
11
12
  class OpraNestAdapter extends core_1.HttpAdapter {
12
- constructor(options) {
13
+ constructor(init, options) {
13
14
  super((function () {
14
15
  const document = new common_2.ApiDocument();
15
16
  document.api = new common_2.HttpApi(document);
16
17
  return document;
17
- })(), options);
18
- // protected _platform: string = 'express';
19
- this.controllers = [];
20
- let basePath = options.basePath || '/';
18
+ })(), {
19
+ ...options,
20
+ interceptors: options?.interceptors,
21
+ });
22
+ this.nestControllers = [];
23
+ this.options = options;
24
+ let basePath = options?.basePath || '/';
21
25
  if (!basePath.startsWith('/'))
22
26
  basePath = '/' + basePath;
23
- if (options.controllers)
24
- options.controllers.forEach(c => this._createNestControllers(c, basePath));
27
+ this._addRootController(basePath);
28
+ if (init.controllers)
29
+ init.controllers.forEach(c => this._addToNestControllers(c, basePath, []));
25
30
  }
26
31
  async close() {
27
32
  //
28
33
  }
29
- _createNestControllers(source, currentPath) {
30
- const metadata = Reflect.getMetadata(common_2.HTTP_CONTROLLER_METADATA, source);
34
+ _addRootController(basePath) {
35
+ const _this = this;
36
+ let RootController = class RootController {
37
+ schema(_req, next) {
38
+ _this.handler.sendDocumentSchema(_req.opraContext).catch(() => next());
39
+ }
40
+ };
41
+ tslib_1.__decorate([
42
+ (0, common_1.Get)('/\\$schema'),
43
+ tslib_1.__param(0, (0, common_1.Req)()),
44
+ tslib_1.__param(1, (0, common_1.Next)()),
45
+ tslib_1.__metadata("design:type", Function),
46
+ tslib_1.__metadata("design:paramtypes", [Object, Function]),
47
+ tslib_1.__metadata("design:returntype", void 0)
48
+ ], RootController.prototype, "schema", null);
49
+ RootController = tslib_1.__decorate([
50
+ (0, common_1.Controller)({
51
+ path: basePath,
52
+ })
53
+ ], RootController);
54
+ if (this.options?.schemaRouteIsPublic) {
55
+ (0, public_decorator_js_1.Public)()(RootController.prototype, 'schema', Object.getOwnPropertyDescriptor(RootController.prototype, 'schema'));
56
+ }
57
+ this.nestControllers.push(RootController);
58
+ }
59
+ _addToNestControllers(sourceClass, currentPath, parentTree) {
60
+ const metadata = Reflect.getMetadata(common_2.HTTP_CONTROLLER_METADATA, sourceClass);
31
61
  if (!metadata)
32
62
  return;
33
63
  const newClass = {
34
- [source.name]: class extends source {
64
+ [sourceClass.name]: class extends sourceClass {
35
65
  },
36
- }[source.name];
66
+ }[sourceClass.name];
67
+ /** Copy metadata keys from source class to new one */
68
+ let metadataKeys;
69
+ OpraNestAdapter.copyDecoratorMetadataToChild(newClass, parentTree);
37
70
  const newPath = metadata.path ? path_1.default.join(currentPath, metadata.path) : currentPath;
38
71
  const adapter = this;
39
- /** Inject exception filter */
40
- (0, common_1.UseFilters)(new opra_exception_filter_js_1.OpraExceptionFilter(adapter))(newClass);
72
+ // adapter.logger =
73
+ /** Disable default error handler. Errors will be handled by OpraExceptionFilter */
74
+ adapter.handler.onError = (context, error) => {
75
+ throw error;
76
+ };
41
77
  (0, common_1.Controller)()(newClass);
42
- this.controllers.push(newClass);
78
+ this.nestControllers.push(newClass);
43
79
  if (metadata.operations) {
44
80
  for (const [k, v] of Object.entries(metadata.operations)) {
45
- const operationHandler = source.prototype[k];
81
+ const operationHandler = sourceClass.prototype[k];
46
82
  Object.defineProperty(newClass.prototype, k, {
47
83
  writable: true,
48
84
  /** NestJS handler method */
49
85
  async value(_req, _res) {
50
- const request = core_1.HttpIncoming.from(_req);
51
- const response = core_1.HttpOutgoing.from(_res);
86
+ _res.statusCode = 200;
52
87
  const api = adapter.document.api;
53
- const controller = api.findController(newClass);
88
+ const controller = api.findController(sourceClass);
54
89
  const operation = controller?.operations.get(k);
55
- if (!(operation && typeof operationHandler === 'function'))
90
+ const context = (0, ts_gems_1.asMutable)(_req.opraContext);
91
+ if (!(context && operation && typeof operationHandler === 'function')) {
56
92
  throw new common_2.NotFoundError({
57
- message: `No endpoint found for [${request.method}]${request.baseUrl}`,
93
+ message: `No endpoint found for [${_req.method}]${_req.baseUrl}`,
58
94
  details: {
59
- path: request.baseUrl,
60
- method: request.method,
95
+ path: _req.baseUrl,
96
+ method: _req.method,
61
97
  },
62
98
  });
63
- /** Create the HttpContext */
64
- const context = new core_1.HttpContext({
65
- adapter,
66
- platform: _req.route ? 'express' : 'fastify',
67
- platformArgs: {
68
- request,
69
- response,
70
- },
71
- request,
72
- response,
73
- operation,
74
- controller: operation.owner,
75
- controllerInstance: this,
76
- operationHandler,
77
- });
99
+ }
100
+ /** Configure the HttpContext */
101
+ context.operation = operation;
102
+ context.controller = operation.owner;
103
+ context.controllerInstance = this;
104
+ context.operationHandler = operationHandler;
78
105
  /** Handle request */
79
- await adapter[exports.kHandler].handleRequest(context);
106
+ await adapter.handler.handleRequest(context);
80
107
  },
81
108
  });
82
- (0, common_1.Req)()(newClass.prototype, k, 0);
83
- (0, common_1.Res)()(newClass.prototype, k, 1);
84
109
  /** Copy metadata keys from source function to new one */
85
- const metadataKeys = Reflect.getOwnMetadataKeys(operationHandler);
110
+ metadataKeys = Reflect.getOwnMetadataKeys(operationHandler);
86
111
  const newFn = newClass.prototype[k];
87
112
  for (const key of metadataKeys) {
88
113
  const m = Reflect.getMetadata(key, operationHandler);
89
114
  Reflect.defineMetadata(key, m, newFn);
90
115
  }
116
+ (0, common_1.Req)()(newClass.prototype, k, 0);
117
+ (0, common_1.Res)()(newClass.prototype, k, 1);
91
118
  const descriptor = Object.getOwnPropertyDescriptor(newClass.prototype, k);
92
- const operationPath = newPath + (v.path || '');
119
+ const operationPath = v.mergePath ? newPath + (v.path || '') : path_1.default.posix.join(newPath, v.path || '');
93
120
  switch (v.method || 'GET') {
94
121
  case 'DELETE':
95
122
  /** Call @Delete decorator over new property */
@@ -123,6 +150,8 @@ class OpraNestAdapter extends core_1.HttpAdapter {
123
150
  /** Call @Search decorator over new property */
124
151
  (0, common_1.Search)(operationPath)(newClass.prototype, k, descriptor);
125
152
  break;
153
+ default:
154
+ break;
126
155
  }
127
156
  }
128
157
  }
@@ -130,7 +159,30 @@ class OpraNestAdapter extends core_1.HttpAdapter {
130
159
  for (const child of metadata.controllers) {
131
160
  if (!(0, common_2.isConstructor)(child))
132
161
  throw new TypeError('Controllers should be injectable a class');
133
- this._createNestControllers(child, newPath);
162
+ this._addToNestControllers(child, newPath, [...parentTree, sourceClass]);
163
+ }
164
+ }
165
+ }
166
+ static copyDecoratorMetadataToChild(target, parentTree) {
167
+ for (const parent of parentTree) {
168
+ const metadataKeys = Reflect.getOwnMetadataKeys(parent);
169
+ for (const key of metadataKeys) {
170
+ if (typeof key === 'string' && key.startsWith('opra:') && !Reflect.hasOwnMetadata(key, target)) {
171
+ const metadata = Reflect.getMetadata(key, parent);
172
+ Reflect.defineMetadata(key, metadata, target);
173
+ continue;
174
+ }
175
+ if (key === constants_1.GUARDS_METADATA || key === constants_1.INTERCEPTORS_METADATA || key === constants_1.EXCEPTION_FILTERS_METADATA) {
176
+ const m1 = Reflect.getMetadata(key, target) || [];
177
+ const metadata = [...m1];
178
+ const m2 = Reflect.getOwnMetadata(key, parent) || [];
179
+ m2.forEach((t) => {
180
+ if (!metadata.includes(t)) {
181
+ metadata.push(t);
182
+ }
183
+ });
184
+ Reflect.defineMetadata(key, metadata, target);
185
+ }
134
186
  }
135
187
  }
136
188
  }
@@ -1,18 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OpraExceptionFilter = exports.kHandler = void 0;
4
- const core_1 = require("@opra/core");
5
- exports.kHandler = Symbol.for('kHandler');
6
- class OpraExceptionFilter {
7
- constructor(adapter) {
8
- this.adapter = adapter;
3
+ exports.OpraExceptionFilter = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const common_1 = require("@nestjs/common");
6
+ const core_1 = require("@nestjs/core");
7
+ const opra_nestjs_adapter_js_1 = require("../opra-nestjs-adapter.js");
8
+ let OpraExceptionFilter = class OpraExceptionFilter extends core_1.BaseExceptionFilter {
9
+ constructor(moduleRef) {
10
+ super();
11
+ this.moduleRef = moduleRef;
9
12
  }
10
13
  catch(exception, host) {
11
- const ctx = host.switchToHttp();
12
- const _res = ctx.getResponse();
13
- const error = (0, core_1.wrapException)(exception);
14
- const response = core_1.HttpOutgoing.from(_res);
15
- return this.adapter[exports.kHandler].sendErrorResponse(response, [error]);
14
+ const ctx = host.switchToHttp().getRequest().opraContext;
15
+ if (ctx) {
16
+ const adapter = this.moduleRef.get(opra_nestjs_adapter_js_1.OpraNestAdapter);
17
+ ctx.errors.push(exception);
18
+ return adapter.handler.sendResponse(ctx);
19
+ }
16
20
  }
17
- }
21
+ };
18
22
  exports.OpraExceptionFilter = OpraExceptionFilter;
23
+ exports.OpraExceptionFilter = OpraExceptionFilter = tslib_1.__decorate([
24
+ (0, common_1.Catch)(),
25
+ tslib_1.__metadata("design:paramtypes", [core_1.ModuleRef])
26
+ ], OpraExceptionFilter);
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OpraMiddleware = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const common_1 = require("@nestjs/common");
6
+ const core_1 = require("@opra/core");
7
+ const constants_1 = require("../constants");
8
+ const opra_nestjs_adapter_js_1 = require("../opra-nestjs-adapter.js");
9
+ let OpraMiddleware = class OpraMiddleware {
10
+ constructor(opraAdapter, options) {
11
+ this.opraAdapter = opraAdapter;
12
+ this.options = options;
13
+ }
14
+ use(req, res, next) {
15
+ const request = core_1.HttpIncoming.from(req);
16
+ const response = core_1.HttpOutgoing.from(res);
17
+ /** Create the HttpContext */
18
+ const context = new core_1.HttpContext({
19
+ adapter: this.opraAdapter,
20
+ platform: req.route ? 'express' : 'fastify',
21
+ request,
22
+ response,
23
+ });
24
+ req.opraContext = context;
25
+ this.opraAdapter
26
+ .emitAsync('createContext', context)
27
+ .then(() => next())
28
+ .catch(next);
29
+ }
30
+ };
31
+ exports.OpraMiddleware = OpraMiddleware;
32
+ exports.OpraMiddleware = OpraMiddleware = tslib_1.__decorate([
33
+ (0, common_1.Injectable)(),
34
+ tslib_1.__param(1, (0, common_1.Inject)(constants_1.OPRA_HTTP_MODULE_OPTIONS)),
35
+ tslib_1.__metadata("design:paramtypes", [opra_nestjs_adapter_js_1.OpraNestAdapter, Object])
36
+ ], OpraMiddleware);
@@ -0,0 +1,2 @@
1
+ export const IS_PUBLIC_KEY = 'opra:isPublic';
2
+ export const OPRA_HTTP_MODULE_OPTIONS = 'OPRA_HTTP_MODULE_OPTIONS';
@@ -0,0 +1,3 @@
1
+ import { SetMetadata } from '@nestjs/common';
2
+ import { IS_PUBLIC_KEY } from '../constants.js';
3
+ export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
package/esm/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import 'reflect-metadata';
2
2
  import './augmentation/nestjs.augmentation.js';
3
+ export * from './constants.js';
4
+ export * from './decorators/public.decorator.js';
3
5
  export * from './opra-http.module.js';
4
6
  export * from './opra-nestjs-adapter.js';
@@ -1,39 +1,69 @@
1
1
  var OpraHttpCoreModule_1;
2
2
  import { __decorate, __metadata } from "tslib";
3
+ import { Global, Module, RequestMethod, } from '@nestjs/common';
4
+ import { APP_FILTER, ModuleRef } from '@nestjs/core';
5
+ import { ApiDocumentFactory, isConstructor } from '@opra/common';
3
6
  import { asMutable } from 'ts-gems';
4
- import { Global, Module } from '@nestjs/common';
5
- import { ApiDocumentFactory } from '@opra/common';
7
+ import { OPRA_HTTP_MODULE_OPTIONS } from './constants';
6
8
  import { OpraNestAdapter } from './opra-nestjs-adapter.js';
9
+ import { OpraExceptionFilter } from './services/opra-exception-filter';
10
+ import { OpraMiddleware } from './services/opra-middleware.js';
7
11
  let OpraHttpCoreModule = OpraHttpCoreModule_1 = class OpraHttpCoreModule {
8
12
  constructor(opraAdapter) {
9
13
  this.opraAdapter = opraAdapter;
10
14
  }
11
- static forRoot(options) {
12
- const opraAdapter = new OpraNestAdapter(options);
13
- const token = options?.id || OpraNestAdapter;
15
+ configure(consumer) {
16
+ consumer.apply(OpraMiddleware).forRoutes({
17
+ path: '*',
18
+ method: RequestMethod.ALL,
19
+ });
20
+ }
21
+ static forRoot(init, options) {
22
+ const opraAdapter = new OpraNestAdapter(init, options);
23
+ const token = init?.id || OpraNestAdapter;
14
24
  const providers = [
15
- ...(options?.providers || []),
25
+ ...(init?.providers || []),
26
+ {
27
+ provide: OPRA_HTTP_MODULE_OPTIONS,
28
+ useValue: { ...options },
29
+ },
16
30
  {
17
31
  provide: OpraNestAdapter,
18
- useFactory: async () => {
32
+ inject: [ModuleRef],
33
+ useFactory: async (moduleRef) => {
19
34
  asMutable(opraAdapter).document = await ApiDocumentFactory.createDocument({
20
- ...options,
21
- api: { protocol: 'http', name: options.name, controllers: opraAdapter.controllers },
35
+ ...init,
36
+ api: { protocol: 'http', name: init.name, controllers: init.controllers },
37
+ });
38
+ opraAdapter.interceptors.map(x => {
39
+ if (isConstructor(x)) {
40
+ return (ctx, next) => {
41
+ const interceptor = moduleRef.get(x);
42
+ if (typeof interceptor.intercept === 'function')
43
+ return interceptor.intercept(ctx, next());
44
+ };
45
+ }
46
+ return x;
22
47
  });
23
48
  return opraAdapter;
24
49
  },
25
50
  },
51
+ {
52
+ provide: APP_FILTER,
53
+ useClass: OpraExceptionFilter,
54
+ },
26
55
  ];
27
- if (token !== OpraNestAdapter)
56
+ if (token !== OpraNestAdapter) {
28
57
  providers.push({
29
58
  provide: token,
30
59
  useValue: opraAdapter,
31
60
  });
61
+ }
32
62
  return {
33
63
  module: OpraHttpCoreModule_1,
34
- controllers: opraAdapter.controllers,
35
- imports: [...(options?.imports || [])],
36
- exports: [...(options?.exports || []), token],
64
+ controllers: opraAdapter.nestControllers,
65
+ imports: [...(init?.imports || [])],
66
+ exports: [...(init?.exports || []), token],
37
67
  providers,
38
68
  };
39
69
  }
@@ -5,12 +5,13 @@ import { OpraHttpCoreModule } from './opra-http-core.module.js';
5
5
  let OpraHttpModule = OpraHttpModule_1 = class OpraHttpModule {
6
6
  /**
7
7
  *
8
+ * @param init
8
9
  * @param options
9
10
  */
10
- static forRoot(options) {
11
+ static forRoot(init, options) {
11
12
  return {
12
13
  module: OpraHttpModule_1,
13
- imports: [OpraHttpCoreModule.forRoot(options)],
14
+ imports: [OpraHttpCoreModule.forRoot(init, options)],
14
15
  };
15
16
  }
16
17
  };
@@ -1,91 +1,119 @@
1
- import nodePath from 'path';
2
- import { Controller, Delete, Get, Head, Options, Patch, Post, Put, Req, Res, Search, UseFilters, } from '@nestjs/common';
1
+ import { __decorate, __metadata, __param } from "tslib";
2
+ import { Controller, Delete, Get, Head, Next, Options, Patch, Post, Put, Req, Res, Search } from '@nestjs/common';
3
+ import { EXCEPTION_FILTERS_METADATA, GUARDS_METADATA, INTERCEPTORS_METADATA } from '@nestjs/common/constants';
3
4
  import { ApiDocument, HTTP_CONTROLLER_METADATA, HttpApi, isConstructor, NotFoundError, } from '@opra/common';
4
- import { HttpAdapter, HttpContext, HttpIncoming, HttpOutgoing } from '@opra/core';
5
- import { OpraExceptionFilter } from './services/opra-exception-filter.js';
6
- export const kHandler = Symbol.for('kHandler');
5
+ import { HttpAdapter } from '@opra/core';
6
+ import nodePath from 'path';
7
+ import { asMutable } from 'ts-gems';
8
+ import { Public } from './decorators/public.decorator.js';
7
9
  export class OpraNestAdapter extends HttpAdapter {
8
- constructor(options) {
10
+ constructor(init, options) {
9
11
  super((function () {
10
12
  const document = new ApiDocument();
11
13
  document.api = new HttpApi(document);
12
14
  return document;
13
- })(), options);
14
- // protected _platform: string = 'express';
15
- this.controllers = [];
16
- let basePath = options.basePath || '/';
15
+ })(), {
16
+ ...options,
17
+ interceptors: options?.interceptors,
18
+ });
19
+ this.nestControllers = [];
20
+ this.options = options;
21
+ let basePath = options?.basePath || '/';
17
22
  if (!basePath.startsWith('/'))
18
23
  basePath = '/' + basePath;
19
- if (options.controllers)
20
- options.controllers.forEach(c => this._createNestControllers(c, basePath));
24
+ this._addRootController(basePath);
25
+ if (init.controllers)
26
+ init.controllers.forEach(c => this._addToNestControllers(c, basePath, []));
21
27
  }
22
28
  async close() {
23
29
  //
24
30
  }
25
- _createNestControllers(source, currentPath) {
26
- const metadata = Reflect.getMetadata(HTTP_CONTROLLER_METADATA, source);
31
+ _addRootController(basePath) {
32
+ const _this = this;
33
+ let RootController = class RootController {
34
+ schema(_req, next) {
35
+ _this.handler.sendDocumentSchema(_req.opraContext).catch(() => next());
36
+ }
37
+ };
38
+ __decorate([
39
+ Get('/\\$schema'),
40
+ __param(0, Req()),
41
+ __param(1, Next()),
42
+ __metadata("design:type", Function),
43
+ __metadata("design:paramtypes", [Object, Function]),
44
+ __metadata("design:returntype", void 0)
45
+ ], RootController.prototype, "schema", null);
46
+ RootController = __decorate([
47
+ Controller({
48
+ path: basePath,
49
+ })
50
+ ], RootController);
51
+ if (this.options?.schemaRouteIsPublic) {
52
+ Public()(RootController.prototype, 'schema', Object.getOwnPropertyDescriptor(RootController.prototype, 'schema'));
53
+ }
54
+ this.nestControllers.push(RootController);
55
+ }
56
+ _addToNestControllers(sourceClass, currentPath, parentTree) {
57
+ const metadata = Reflect.getMetadata(HTTP_CONTROLLER_METADATA, sourceClass);
27
58
  if (!metadata)
28
59
  return;
29
60
  const newClass = {
30
- [source.name]: class extends source {
61
+ [sourceClass.name]: class extends sourceClass {
31
62
  },
32
- }[source.name];
63
+ }[sourceClass.name];
64
+ /** Copy metadata keys from source class to new one */
65
+ let metadataKeys;
66
+ OpraNestAdapter.copyDecoratorMetadataToChild(newClass, parentTree);
33
67
  const newPath = metadata.path ? nodePath.join(currentPath, metadata.path) : currentPath;
34
68
  const adapter = this;
35
- /** Inject exception filter */
36
- UseFilters(new OpraExceptionFilter(adapter))(newClass);
69
+ // adapter.logger =
70
+ /** Disable default error handler. Errors will be handled by OpraExceptionFilter */
71
+ adapter.handler.onError = (context, error) => {
72
+ throw error;
73
+ };
37
74
  Controller()(newClass);
38
- this.controllers.push(newClass);
75
+ this.nestControllers.push(newClass);
39
76
  if (metadata.operations) {
40
77
  for (const [k, v] of Object.entries(metadata.operations)) {
41
- const operationHandler = source.prototype[k];
78
+ const operationHandler = sourceClass.prototype[k];
42
79
  Object.defineProperty(newClass.prototype, k, {
43
80
  writable: true,
44
81
  /** NestJS handler method */
45
82
  async value(_req, _res) {
46
- const request = HttpIncoming.from(_req);
47
- const response = HttpOutgoing.from(_res);
83
+ _res.statusCode = 200;
48
84
  const api = adapter.document.api;
49
- const controller = api.findController(newClass);
85
+ const controller = api.findController(sourceClass);
50
86
  const operation = controller?.operations.get(k);
51
- if (!(operation && typeof operationHandler === 'function'))
87
+ const context = asMutable(_req.opraContext);
88
+ if (!(context && operation && typeof operationHandler === 'function')) {
52
89
  throw new NotFoundError({
53
- message: `No endpoint found for [${request.method}]${request.baseUrl}`,
90
+ message: `No endpoint found for [${_req.method}]${_req.baseUrl}`,
54
91
  details: {
55
- path: request.baseUrl,
56
- method: request.method,
92
+ path: _req.baseUrl,
93
+ method: _req.method,
57
94
  },
58
95
  });
59
- /** Create the HttpContext */
60
- const context = new HttpContext({
61
- adapter,
62
- platform: _req.route ? 'express' : 'fastify',
63
- platformArgs: {
64
- request,
65
- response,
66
- },
67
- request,
68
- response,
69
- operation,
70
- controller: operation.owner,
71
- controllerInstance: this,
72
- operationHandler,
73
- });
96
+ }
97
+ /** Configure the HttpContext */
98
+ context.operation = operation;
99
+ context.controller = operation.owner;
100
+ context.controllerInstance = this;
101
+ context.operationHandler = operationHandler;
74
102
  /** Handle request */
75
- await adapter[kHandler].handleRequest(context);
103
+ await adapter.handler.handleRequest(context);
76
104
  },
77
105
  });
78
- Req()(newClass.prototype, k, 0);
79
- Res()(newClass.prototype, k, 1);
80
106
  /** Copy metadata keys from source function to new one */
81
- const metadataKeys = Reflect.getOwnMetadataKeys(operationHandler);
107
+ metadataKeys = Reflect.getOwnMetadataKeys(operationHandler);
82
108
  const newFn = newClass.prototype[k];
83
109
  for (const key of metadataKeys) {
84
110
  const m = Reflect.getMetadata(key, operationHandler);
85
111
  Reflect.defineMetadata(key, m, newFn);
86
112
  }
113
+ Req()(newClass.prototype, k, 0);
114
+ Res()(newClass.prototype, k, 1);
87
115
  const descriptor = Object.getOwnPropertyDescriptor(newClass.prototype, k);
88
- const operationPath = newPath + (v.path || '');
116
+ const operationPath = v.mergePath ? newPath + (v.path || '') : nodePath.posix.join(newPath, v.path || '');
89
117
  switch (v.method || 'GET') {
90
118
  case 'DELETE':
91
119
  /** Call @Delete decorator over new property */
@@ -119,6 +147,8 @@ export class OpraNestAdapter extends HttpAdapter {
119
147
  /** Call @Search decorator over new property */
120
148
  Search(operationPath)(newClass.prototype, k, descriptor);
121
149
  break;
150
+ default:
151
+ break;
122
152
  }
123
153
  }
124
154
  }
@@ -126,7 +156,30 @@ export class OpraNestAdapter extends HttpAdapter {
126
156
  for (const child of metadata.controllers) {
127
157
  if (!isConstructor(child))
128
158
  throw new TypeError('Controllers should be injectable a class');
129
- this._createNestControllers(child, newPath);
159
+ this._addToNestControllers(child, newPath, [...parentTree, sourceClass]);
160
+ }
161
+ }
162
+ }
163
+ static copyDecoratorMetadataToChild(target, parentTree) {
164
+ for (const parent of parentTree) {
165
+ const metadataKeys = Reflect.getOwnMetadataKeys(parent);
166
+ for (const key of metadataKeys) {
167
+ if (typeof key === 'string' && key.startsWith('opra:') && !Reflect.hasOwnMetadata(key, target)) {
168
+ const metadata = Reflect.getMetadata(key, parent);
169
+ Reflect.defineMetadata(key, metadata, target);
170
+ continue;
171
+ }
172
+ if (key === GUARDS_METADATA || key === INTERCEPTORS_METADATA || key === EXCEPTION_FILTERS_METADATA) {
173
+ const m1 = Reflect.getMetadata(key, target) || [];
174
+ const metadata = [...m1];
175
+ const m2 = Reflect.getOwnMetadata(key, parent) || [];
176
+ m2.forEach((t) => {
177
+ if (!metadata.includes(t)) {
178
+ metadata.push(t);
179
+ }
180
+ });
181
+ Reflect.defineMetadata(key, metadata, target);
182
+ }
130
183
  }
131
184
  }
132
185
  }
@@ -1,14 +1,23 @@
1
- import { HttpOutgoing, wrapException } from '@opra/core';
2
- export const kHandler = Symbol.for('kHandler');
3
- export class OpraExceptionFilter {
4
- constructor(adapter) {
5
- this.adapter = adapter;
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { Catch } from '@nestjs/common';
3
+ import { BaseExceptionFilter, ModuleRef } from '@nestjs/core';
4
+ import { OpraNestAdapter } from '../opra-nestjs-adapter.js';
5
+ let OpraExceptionFilter = class OpraExceptionFilter extends BaseExceptionFilter {
6
+ constructor(moduleRef) {
7
+ super();
8
+ this.moduleRef = moduleRef;
6
9
  }
7
10
  catch(exception, host) {
8
- const ctx = host.switchToHttp();
9
- const _res = ctx.getResponse();
10
- const error = wrapException(exception);
11
- const response = HttpOutgoing.from(_res);
12
- return this.adapter[kHandler].sendErrorResponse(response, [error]);
11
+ const ctx = host.switchToHttp().getRequest().opraContext;
12
+ if (ctx) {
13
+ const adapter = this.moduleRef.get(OpraNestAdapter);
14
+ ctx.errors.push(exception);
15
+ return adapter.handler.sendResponse(ctx);
16
+ }
13
17
  }
14
- }
18
+ };
19
+ OpraExceptionFilter = __decorate([
20
+ Catch(),
21
+ __metadata("design:paramtypes", [ModuleRef])
22
+ ], OpraExceptionFilter);
23
+ export { OpraExceptionFilter };
@@ -0,0 +1,33 @@
1
+ import { __decorate, __metadata, __param } from "tslib";
2
+ import { Inject, Injectable } from '@nestjs/common';
3
+ import { HttpContext, HttpIncoming, HttpOutgoing } from '@opra/core';
4
+ import { OPRA_HTTP_MODULE_OPTIONS } from '../constants';
5
+ import { OpraNestAdapter } from '../opra-nestjs-adapter.js';
6
+ let OpraMiddleware = class OpraMiddleware {
7
+ constructor(opraAdapter, options) {
8
+ this.opraAdapter = opraAdapter;
9
+ this.options = options;
10
+ }
11
+ use(req, res, next) {
12
+ const request = HttpIncoming.from(req);
13
+ const response = HttpOutgoing.from(res);
14
+ /** Create the HttpContext */
15
+ const context = new HttpContext({
16
+ adapter: this.opraAdapter,
17
+ platform: req.route ? 'express' : 'fastify',
18
+ request,
19
+ response,
20
+ });
21
+ req.opraContext = context;
22
+ this.opraAdapter
23
+ .emitAsync('createContext', context)
24
+ .then(() => next())
25
+ .catch(next);
26
+ }
27
+ };
28
+ OpraMiddleware = __decorate([
29
+ Injectable(),
30
+ __param(1, Inject(OPRA_HTTP_MODULE_OPTIONS)),
31
+ __metadata("design:paramtypes", [OpraNestAdapter, Object])
32
+ ], OpraMiddleware);
33
+ export { OpraMiddleware };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opra/nestjs",
3
- "version": "1.0.0-alpha.3",
3
+ "version": "1.0.0-alpha.30",
4
4
  "description": "Opra NestJS module",
5
5
  "author": "Panates",
6
6
  "license": "MIT",
@@ -18,8 +18,8 @@
18
18
  "postbuild": "cp README.md package.json ../../LICENSE ../../build/nestjs && cp ../../package.cjs.json ../../build/nestjs/cjs/package.json",
19
19
  "lint": "eslint . --max-warnings=0",
20
20
  "format": "prettier . --write --log-level=warn",
21
- "test": "jest",
22
- "cover": "jest --collect-coverage",
21
+ "test": "jest --passWithNoTests",
22
+ "cover": "jest --passWithNoTests --collect-coverage",
23
23
  "clean": "npm run clean:src && npm run clean:test && npm run clean:dist && npm run clean:cover",
24
24
  "clean:src": "ts-cleanup -s src --all",
25
25
  "clean:test": "ts-cleanup -s test --all",
@@ -27,21 +27,26 @@
27
27
  "clean:cover": "rimraf ../../coverage/client"
28
28
  },
29
29
  "dependencies": {
30
- "@opra/common": "^1.0.0-alpha.3",
31
- "@opra/core": "^1.0.0-alpha.3",
30
+ "@opra/common": "^1.0.0-alpha.30",
31
+ "@opra/core": "^1.0.0-alpha.30",
32
32
  "fast-tokenizer": "^1.3.0",
33
33
  "lodash.head": "^4.0.1",
34
- "reflect-metadata": "^0.2.2"
34
+ "putil-promisify": "^1.10.1",
35
+ "reflect-metadata": "^0.2.2",
36
+ "tslib": "^2.6.3"
35
37
  },
36
38
  "peerDependencies": {
37
- "@nestjs/common": "^10.3.9",
38
- "@nestjs/core": "^10.3.9"
39
+ "@nestjs/common": "^10.3.10",
40
+ "@nestjs/core": "^10.3.10"
39
41
  },
40
42
  "devDependencies": {
41
- "@nestjs/platform-express": "^10.3.9",
42
- "@nestjs/testing": "^10.3.9",
43
+ "@nestjs/platform-express": "^10.3.10",
44
+ "@nestjs/testing": "^10.3.10",
43
45
  "@types/lodash.head": "^4.0.9",
46
+ "express": "^4.19.2",
44
47
  "filedirname": "^3.4.0",
48
+ "rxjs": "^7.8.1",
49
+ "supertest": "^7.0.0",
45
50
  "ts-gems": "^3.4.0"
46
51
  },
47
52
  "type": "module",
@@ -0,0 +1,2 @@
1
+ export declare const IS_PUBLIC_KEY = "opra:isPublic";
2
+ export declare const OPRA_HTTP_MODULE_OPTIONS = "OPRA_HTTP_MODULE_OPTIONS";
@@ -0,0 +1 @@
1
+ export declare const Public: () => import("@nestjs/common").CustomDecorator<string>;
package/types/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import 'reflect-metadata';
2
2
  import './augmentation/nestjs.augmentation.js';
3
+ export * from './constants.js';
4
+ export * from './decorators/public.decorator.js';
3
5
  export * from './opra-http.module.js';
4
6
  export * from './opra-nestjs-adapter.js';
@@ -1,9 +1,10 @@
1
- import { DynamicModule, OnModuleDestroy } from '@nestjs/common';
2
- import type { OpraHttpModule } from './opra-http.module';
1
+ import { DynamicModule, MiddlewareConsumer, NestModule, OnModuleDestroy } from '@nestjs/common';
2
+ import type { OpraHttpModule } from './opra-http.module.js';
3
3
  import { OpraNestAdapter } from './opra-nestjs-adapter.js';
4
- export declare class OpraHttpCoreModule implements OnModuleDestroy {
4
+ export declare class OpraHttpCoreModule implements OnModuleDestroy, NestModule {
5
5
  protected opraAdapter: OpraNestAdapter;
6
6
  constructor(opraAdapter: OpraNestAdapter);
7
- static forRoot(options: OpraHttpModule.Options): DynamicModule;
7
+ configure(consumer: MiddlewareConsumer): void;
8
+ static forRoot(init: OpraHttpModule.Initiator, options?: OpraHttpModule.Options): DynamicModule;
8
9
  onModuleDestroy(): Promise<void>;
9
10
  }
@@ -1,16 +1,22 @@
1
- import { DynamicModule } from '@nestjs/common';
1
+ import { DynamicModule, Type } from '@nestjs/common';
2
2
  import { ApiDocumentFactory } from '@opra/common';
3
+ import { HttpAdapter } from '@opra/core';
3
4
  export declare namespace OpraHttpModule {
4
- interface Options extends Pick<DynamicModule, 'imports' | 'providers' | 'exports' | 'controllers'>, Pick<ApiDocumentFactory.InitArguments, 'types' | 'references' | 'info'> {
5
+ interface Initiator extends Pick<DynamicModule, 'imports' | 'providers' | 'exports' | 'controllers'>, Pick<ApiDocumentFactory.InitArguments, 'types' | 'references' | 'info'> {
5
6
  id?: any;
6
7
  name: string;
8
+ }
9
+ interface Options {
7
10
  basePath?: string;
11
+ schemaRouteIsPublic?: boolean;
12
+ interceptors?: (HttpAdapter.InterceptorFunction | HttpAdapter.IHttpInterceptor | Type<HttpAdapter.IHttpInterceptor>)[];
8
13
  }
9
14
  }
10
15
  export declare class OpraHttpModule {
11
16
  /**
12
17
  *
18
+ * @param init
13
19
  * @param options
14
20
  */
15
- static forRoot(options: OpraHttpModule.Options): DynamicModule;
21
+ static forRoot(init: OpraHttpModule.Initiator, options?: OpraHttpModule.Options): DynamicModule;
16
22
  }
@@ -1,10 +1,12 @@
1
1
  import { Type } from '@nestjs/common';
2
2
  import { HttpAdapter } from '@opra/core';
3
- import type { OpraHttpModule } from './opra-http.module';
4
- export declare const kHandler: unique symbol;
3
+ import type { OpraHttpModule } from './opra-http.module.js';
5
4
  export declare class OpraNestAdapter extends HttpAdapter {
6
- readonly controllers: Type[];
7
- constructor(options: OpraHttpModule.Options);
5
+ readonly nestControllers: Type[];
6
+ readonly options?: OpraHttpModule.Options;
7
+ constructor(init: OpraHttpModule.Initiator, options?: OpraHttpModule.Options);
8
8
  close(): Promise<void>;
9
- protected _createNestControllers(source: Type, currentPath: string): void;
9
+ protected _addRootController(basePath: string): void;
10
+ protected _addToNestControllers(sourceClass: Type, currentPath: string, parentTree: Type[]): void;
11
+ static copyDecoratorMetadataToChild(target: Type, parentTree: Type[]): void;
10
12
  }
@@ -1,8 +1,7 @@
1
- import { ArgumentsHost, ExceptionFilter } from '@nestjs/common';
2
- import { OpraNestAdapter } from '../opra-nestjs-adapter.js';
3
- export declare const kHandler: unique symbol;
4
- export declare class OpraExceptionFilter implements ExceptionFilter {
5
- readonly adapter: OpraNestAdapter;
6
- constructor(adapter: OpraNestAdapter);
7
- catch(exception: any, host: ArgumentsHost): Promise<void>;
1
+ import { ArgumentsHost } from '@nestjs/common';
2
+ import { BaseExceptionFilter, ModuleRef } from '@nestjs/core';
3
+ export declare class OpraExceptionFilter extends BaseExceptionFilter {
4
+ private moduleRef;
5
+ constructor(moduleRef: ModuleRef);
6
+ catch(exception: any, host: ArgumentsHost): Promise<void> | undefined;
8
7
  }
@@ -0,0 +1,10 @@
1
+ import { NestMiddleware } from '@nestjs/common';
2
+ import type { NextFunction, Request, Response } from 'express';
3
+ import type { OpraHttpModule } from '../opra-http.module.js';
4
+ import { OpraNestAdapter } from '../opra-nestjs-adapter.js';
5
+ export declare class OpraMiddleware implements NestMiddleware {
6
+ protected opraAdapter: OpraNestAdapter;
7
+ protected options: OpraHttpModule.Options;
8
+ constructor(opraAdapter: OpraNestAdapter, options: OpraHttpModule.Options);
9
+ use(req: Request, res: Response, next: NextFunction): void;
10
+ }