@open-norantec/herbal 1.0.2-alpha.9 → 1.0.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.
package/dist/core.js CHANGED
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
14
  if (k2 === undefined) k2 = k;
4
15
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -22,9 +33,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
22
33
  var __metadata = (this && this.__metadata) || function (k, v) {
23
34
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
24
35
  };
25
- var __param = (this && this.__param) || function (paramIndex, decorator) {
26
- return function (target, key) { decorator(target, key, paramIndex); }
27
- };
28
36
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
37
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
38
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -61,104 +69,525 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
61
69
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
70
  }
63
71
  };
72
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
73
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
74
+ var m = o[Symbol.asyncIterator], i;
75
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
76
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
77
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
78
+ };
79
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
80
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
81
+ if (ar || !(i in from)) {
82
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
83
+ ar[i] = from[i];
84
+ }
85
+ }
86
+ return to.concat(ar || Array.prototype.slice.call(from));
87
+ };
64
88
  Object.defineProperty(exports, "__esModule", { value: true });
65
- exports.HerbalController = void 0;
89
+ exports.ControllerUtil = exports.getMethodPool = exports.getControllerName = exports.isHerbalController = void 0;
66
90
  require("reflect-metadata");
67
91
  var common_1 = require("@nestjs/common");
68
92
  var header_util_class_1 = require("@open-norantec/utilities/dist/header-util.class");
69
93
  var zod_1 = require("zod");
70
- var _ = require("lodash");
71
94
  var string_util_class_1 = require("@open-norantec/utilities/dist/string-util.class");
95
+ var utilities_1 = require("@open-norantec/utilities");
96
+ require("reflect-metadata");
97
+ var common_2 = require("@nestjs/common");
98
+ var _ = require("lodash");
99
+ var uuid_util_class_1 = require("@open-norantec/utilities/dist/uuid-util.class");
100
+ var common_3 = require("@nestjs/common");
101
+ var headers_constant_1 = require("./constants/headers.constant");
102
+ var core_1 = require("@nestjs/core");
103
+ var auth_adapter_decorator_1 = require("./decorators/auth-adapter.decorator");
104
+ var rxjs_1 = require("rxjs");
105
+ var operators_1 = require("rxjs/operators");
106
+ var logger_service_1 = require("./modules/logger/logger.service");
107
+ var sequelize_typescript_1 = require("sequelize-typescript");
108
+ var decorators_1 = require("./decorators");
109
+ var zod_openapi_1 = require("zod-openapi");
72
110
  __exportStar(require("@nestjs/core"), exports);
73
- var HerbalController = exports.HerbalController = (function () {
74
- function HerbalController() {
75
- var _this = this;
76
- this.registerMethod = function (inputSchema, outputSchema, callback) {
77
- return function (request, rawInput, headers) { return __awaiter(_this, void 0, void 0, function () {
78
- var input, responseData;
79
- var _a, _b, _c;
80
- return __generator(this, function (_d) {
81
- switch (_d.label) {
82
- case 0:
83
- input = inputSchema instanceof zod_1.ZodAny ? rawInput : _.attempt(function () { return inputSchema.parse(rawInput); });
84
- if (input instanceof Error) {
85
- if (input instanceof zod_1.ZodError) {
86
- throw new common_1.BadRequestException({
87
- invalidParams: (_c = (_b = (_a = input === null || input === void 0 ? void 0 : input.issues) === null || _a === void 0 ? void 0 : _a.map) === null || _b === void 0 ? void 0 : _b.call(_a, function (item) { var _a, _b; return (_b = (_a = item === null || item === void 0 ? void 0 : item.path) === null || _a === void 0 ? void 0 : _a.join) === null || _b === void 0 ? void 0 : _b.call(_a, '.'); })) !== null && _c !== void 0 ? _c : [],
88
- });
89
- }
90
- throw input;
91
- }
92
- return [4, callback({ input: input, headers: headers, request: request })];
93
- case 1:
94
- responseData = _d.sent();
95
- return [2, {
96
- request: input,
97
- response: outputSchema instanceof zod_1.ZodAny ? responseData : outputSchema.parse(responseData),
98
- }];
99
- }
100
- });
101
- }); };
102
- };
111
+ var HANDLE_REQUEST_INSTANCE_SYMBOL = '$handleRequestInstance';
112
+ var METHOD_POOL = Symbol();
113
+ var MethodConfig = (function () {
114
+ function MethodConfig(name, options, callback) {
115
+ this.name = name;
116
+ this.options = options;
117
+ this.callback = callback;
103
118
  }
104
- HerbalController.prototype.handler = function (request) {
119
+ MethodConfig.prototype.call = function (controller, callContext) {
105
120
  var _a, _b, _c, _d, _e, _f;
106
121
  return __awaiter(this, void 0, void 0, function () {
107
- var methodHandler, parsedBody, result, _g, _h, error_1;
108
- var _j;
109
- return __generator(this, function (_k) {
110
- switch (_k.label) {
122
+ var inputSchema, outputSchema, parsedBody_1, input, rawResponse_1, response, error_1;
123
+ return __generator(this, function (_g) {
124
+ switch (_g.label) {
111
125
  case 0:
112
- methodHandler = this[request === null || request === void 0 ? void 0 : request.methodName];
113
- parsedBody = _.attempt(function () { return JSON.parse((request === null || request === void 0 ? void 0 : request.rawBody) || ''); });
114
- _k.label = 1;
126
+ inputSchema = this.options.inputSchema;
127
+ outputSchema = this.options.outputSchema;
128
+ _g.label = 1;
115
129
  case 1:
116
- _k.trys.push([1, 12, , 13]);
117
- if (!(typeof methodHandler === 'function')) return [3, 7];
118
- _j = {};
119
- return [4, methodHandler(request, parsedBody instanceof Error ? undefined : parsedBody, header_util_class_1.HeaderUtil.parse((_a = request.headers) !== null && _a !== void 0 ? _a : {})).then(function (response) { return response === null || response === void 0 ? void 0 : response.response; })];
130
+ _g.trys.push([1, 3, , 4]);
131
+ parsedBody_1 = _.attempt(function () { return JSON.parse((callContext === null || callContext === void 0 ? void 0 : callContext.rawBody) || ''); });
132
+ input = _.attempt(function () { return (parsedBody_1 instanceof Error ? undefined : inputSchema.parse(parsedBody_1)); });
133
+ if (input instanceof zod_1.ZodError) {
134
+ throw new common_2.BadRequestException({
135
+ from: 'request',
136
+ invalidParams: (_c = (_b = (_a = input === null || input === void 0 ? void 0 : input.issues) === null || _a === void 0 ? void 0 : _a.map) === null || _b === void 0 ? void 0 : _b.call(_a, function (item) { var _a, _b; return (_b = (_a = item === null || item === void 0 ? void 0 : item.path) === null || _a === void 0 ? void 0 : _a.join) === null || _b === void 0 ? void 0 : _b.call(_a, '.'); })) !== null && _c !== void 0 ? _c : [],
137
+ });
138
+ }
139
+ else if (input instanceof Error)
140
+ throw input;
141
+ return [4, this.callback.call(controller, __assign(__assign({}, callContext), { input: input }))];
120
142
  case 2:
121
- result = (_j.data = _k.sent(),
122
- _j.token = string_util_class_1.StringUtil.isFalsyString((_b = request === null || request === void 0 ? void 0 : request.authenticateResult) === null || _b === void 0 ? void 0 : _b.nextToken)
123
- ? null
124
- : request.authenticateResult.nextToken,
125
- _j);
126
- _k.label = 3;
143
+ rawResponse_1 = _g.sent();
144
+ response = _.attempt(function () { return outputSchema.parse(rawResponse_1); });
145
+ if (response instanceof zod_1.ZodError) {
146
+ throw new common_2.BadRequestException({
147
+ from: 'response',
148
+ invalidParams: (_f = (_e = (_d = response === null || response === void 0 ? void 0 : response.issues) === null || _d === void 0 ? void 0 : _d.map) === null || _e === void 0 ? void 0 : _e.call(_d, function (item) { var _a, _b; return (_b = (_a = item === null || item === void 0 ? void 0 : item.path) === null || _a === void 0 ? void 0 : _a.join) === null || _b === void 0 ? void 0 : _b.call(_a, '.'); })) !== null && _f !== void 0 ? _f : [],
149
+ });
150
+ }
151
+ else if (response instanceof Error)
152
+ throw response;
153
+ return [2, response];
127
154
  case 3:
128
- _k.trys.push([3, 5, , 6]);
129
- return [4, ((_d = (_c = request === null || request === void 0 ? void 0 : request.transaction) === null || _c === void 0 ? void 0 : _c.commit) === null || _d === void 0 ? void 0 : _d.call(_c))];
130
- case 4:
131
- _k.sent();
132
- return [3, 6];
133
- case 5:
134
- _g = _k.sent();
135
- return [3, 6];
136
- case 6: return [2, result];
137
- case 7:
138
- _k.trys.push([7, 9, , 10]);
139
- return [4, ((_f = (_e = request === null || request === void 0 ? void 0 : request.transaction) === null || _e === void 0 ? void 0 : _e.rollback) === null || _f === void 0 ? void 0 : _f.call(_e))];
140
- case 8:
141
- _k.sent();
142
- return [3, 10];
143
- case 9:
144
- _h = _k.sent();
145
- return [3, 10];
146
- case 10: throw new common_1.NotFoundException();
147
- case 11: return [3, 13];
148
- case 12:
149
- error_1 = _k.sent();
155
+ error_1 = _g.sent();
150
156
  throw error_1;
151
- case 13: return [2];
157
+ case 4: return [2];
152
158
  }
153
159
  });
154
160
  });
155
161
  };
156
- __decorate([
157
- (0, common_1.Post)('*'),
158
- __param(0, (0, common_1.Req)()),
159
- __metadata("design:type", Function),
160
- __metadata("design:paramtypes", [Object]),
161
- __metadata("design:returntype", Promise)
162
- ], HerbalController.prototype, "handler", null);
163
- return HerbalController;
162
+ return MethodConfig;
163
+ }());
164
+ var MethodPool = (function () {
165
+ function MethodPool() {
166
+ this.methods = new Map();
167
+ }
168
+ MethodPool.prototype.registerMethod = function (name, options, callback) {
169
+ if (string_util_class_1.StringUtil.isFalsyString(name))
170
+ return;
171
+ if (name.includes('/'))
172
+ throw new Error("Method name cannot contain slashes: ".concat(name));
173
+ this.methods.set(name, new MethodConfig(name, options, callback));
174
+ };
175
+ MethodPool.prototype.transactionDisabled = function (name) {
176
+ var _a, _b;
177
+ if (string_util_class_1.StringUtil.isFalsyString(name))
178
+ return;
179
+ if (name.includes('/'))
180
+ throw new Error("Method name cannot contain slashes: ".concat(name));
181
+ return !!((_b = (_a = this.methods.get(name)) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.disableTransaction);
182
+ };
183
+ MethodPool.prototype.getCallFn = function (name) {
184
+ var config = this.methods.get(name);
185
+ if (!(config instanceof MethodConfig))
186
+ return null;
187
+ return config.call.bind(config);
188
+ };
189
+ MethodPool.prototype.getAuthAdapters = function (name) {
190
+ var config = this.methods.get(name);
191
+ if (!(config instanceof MethodConfig))
192
+ return null;
193
+ return config.options.authAdapters;
194
+ };
195
+ MethodPool.prototype.getOpenAPIPathsObject = function (group) {
196
+ var result = {};
197
+ Array.from(this.methods.entries()).forEach(function (_a) {
198
+ var _b;
199
+ var name = _a[0], config = _a[1];
200
+ var defaultGroupName = "".concat(Date.now(), "_").concat(Math.random().toString(16).slice(2));
201
+ var currentGroupName = string_util_class_1.StringUtil.isFalsyString(group) ? defaultGroupName : group;
202
+ var clientGroups = typeof config.options.clientGroups === 'function'
203
+ ? config.options.clientGroups(defaultGroupName)
204
+ : (_b = config === null || config === void 0 ? void 0 : config.options) === null || _b === void 0 ? void 0 : _b.clientGroups;
205
+ if (!Array.isArray(clientGroups) && !string_util_class_1.StringUtil.isFalsyString(group) && defaultGroupName !== group)
206
+ return;
207
+ if (Array.isArray(clientGroups) && !clientGroups.includes(currentGroupName))
208
+ return;
209
+ result["/".concat(name)] = {
210
+ post: {
211
+ requestBody: {
212
+ description: 'Request body for method ' + name,
213
+ required: true,
214
+ content: {
215
+ 'application/json': {
216
+ schema: (0, zod_openapi_1.createSchema)(config.options.inputSchema).schema,
217
+ },
218
+ },
219
+ },
220
+ responses: {
221
+ '200': {
222
+ description: 'Response for method ' + name,
223
+ content: {
224
+ 'application/json': (0, zod_openapi_1.createSchema)(zod_1.z.object({
225
+ data: config.options.outputSchema,
226
+ token: zod_1.z.string().nullable(),
227
+ })),
228
+ },
229
+ },
230
+ },
231
+ },
232
+ };
233
+ });
234
+ return result;
235
+ };
236
+ return MethodPool;
237
+ }());
238
+ var IS_HERBAL_CONTROLLER = Symbol();
239
+ var CONTROLLER_NAME = Symbol();
240
+ function isHerbalController(target) {
241
+ return _.attempt(function () { return Reflect.getMetadata(IS_HERBAL_CONTROLLER, target.prototype); }) === true;
242
+ }
243
+ exports.isHerbalController = isHerbalController;
244
+ function getControllerName(target) {
245
+ return Reflect.getMetadata(CONTROLLER_NAME, target.prototype);
246
+ }
247
+ exports.getControllerName = getControllerName;
248
+ var ControllerInterceptor = (function () {
249
+ function ControllerInterceptor(ref) {
250
+ this.ref = ref;
251
+ }
252
+ ControllerInterceptor.prototype.intercept = function (context, next) {
253
+ var _this = this;
254
+ var request = context.switchToHttp().getRequest();
255
+ if (isHerbalController(context.getClass())) {
256
+ _.attempt(function () {
257
+ _this.getLogger().log("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":response:url] ").concat(request === null || request === void 0 ? void 0 : request.originalUrl));
258
+ });
259
+ _.attempt(function () {
260
+ return _this.getLogger().log("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":request:headers] ").concat(JSON.stringify(request === null || request === void 0 ? void 0 : request.headers)));
261
+ });
262
+ return this.handle(next, request);
263
+ }
264
+ return next.handle();
265
+ };
266
+ ControllerInterceptor.prototype.getLogger = function () {
267
+ var loggerService = this.ref.get(logger_service_1.LoggerService, { strict: false });
268
+ if (!(loggerService instanceof logger_service_1.LoggerService)) {
269
+ return {
270
+ log: function () { },
271
+ error: function () { },
272
+ };
273
+ }
274
+ return loggerService;
275
+ };
276
+ ControllerInterceptor.prototype.handle = function (next, request) {
277
+ var _this = this;
278
+ return next.handle().pipe((0, operators_1.map)(function (data) {
279
+ _.attempt(function () {
280
+ _this.getLogger().log("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":response:raw] ").concat(JSON.stringify(data)));
281
+ });
282
+ _.attempt(function () {
283
+ _this.getLogger().log("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":response:final] ").concat(JSON.stringify(data)));
284
+ });
285
+ return data;
286
+ }), (0, operators_1.catchError)(function (error) {
287
+ _.attempt(function () {
288
+ _this.getLogger().error("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":response:error:message] ").concat(error === null || error === void 0 ? void 0 : error.message));
289
+ });
290
+ _.attempt(function () {
291
+ _this.getLogger().error("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":response:error:stack] ").concat(error === null || error === void 0 ? void 0 : error.stack));
292
+ });
293
+ _this.getLogger().error("Got error when handling route in interceptor: ".concat(error === null || error === void 0 ? void 0 : error.message, " ").concat(error === null || error === void 0 ? void 0 : error.stack));
294
+ _.attempt(function () { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = request === null || request === void 0 ? void 0 : request.transaction) === null || _a === void 0 ? void 0 : _a.rollback) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.catch) === null || _d === void 0 ? void 0 : _d.call(_c, function () { }); });
295
+ return (0, rxjs_1.throwError)(function () { return error; });
296
+ }));
297
+ };
298
+ ControllerInterceptor = __decorate([
299
+ (0, common_3.Injectable)(),
300
+ __metadata("design:paramtypes", [core_1.ModuleRef])
301
+ ], ControllerInterceptor);
302
+ return ControllerInterceptor;
303
+ }());
304
+ function HerbalGuard(options) {
305
+ var HerbalGuardMixin = (function () {
306
+ function HerbalGuardMixin(ref) {
307
+ this.ref = ref;
308
+ }
309
+ HerbalGuardMixin.prototype.canActivate = function (context) {
310
+ var _a, e_1, _b, _c;
311
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m;
312
+ return __awaiter(this, void 0, void 0, function () {
313
+ var sequelizeInstance, transaction, request, response, traceId, chunks, _o, request_1, request_1_1, chunk, e_1_1, _p, parsedBody, rawHandlerName, handlerPropertype, handlerName, methodPool, authAdapters, error_2, _i, authAdapters_1, AuthAdapterClass, adapter, authenticateResult, error_3, _q;
314
+ var _this = this;
315
+ return __generator(this, function (_r) {
316
+ switch (_r.label) {
317
+ case 0:
318
+ sequelizeInstance = _.attempt(function () { return _this.ref.get(sequelize_typescript_1.Sequelize, { strict: false }); });
319
+ transaction = undefined;
320
+ request = context.switchToHttp().getRequest();
321
+ response = context.switchToHttp().getResponse();
322
+ traceId = typeof (options === null || options === void 0 ? void 0 : options.getTraceId) === 'function'
323
+ ? _.attempt(function () { return options.getTraceId(request); })
324
+ : uuid_util_class_1.UUIDUtil.generateV4();
325
+ if (traceId instanceof Error || string_util_class_1.StringUtil.isFalsyString(traceId))
326
+ traceId = uuid_util_class_1.UUIDUtil.generateV4();
327
+ request.traceId = traceId;
328
+ request.methodName = request.url.split('/').pop();
329
+ response.setHeader(headers_constant_1.HEADERS.TRACE_ID, traceId);
330
+ chunks = [];
331
+ _r.label = 1;
332
+ case 1:
333
+ _r.trys.push([1, 14, , 15]);
334
+ _r.label = 2;
335
+ case 2:
336
+ _r.trys.push([2, 7, 8, 13]);
337
+ _o = true, request_1 = __asyncValues(request);
338
+ _r.label = 3;
339
+ case 3: return [4, request_1.next()];
340
+ case 4:
341
+ if (!(request_1_1 = _r.sent(), _a = request_1_1.done, !_a)) return [3, 6];
342
+ _c = request_1_1.value;
343
+ _o = false;
344
+ chunk = _c;
345
+ chunks.push(chunk);
346
+ _r.label = 5;
347
+ case 5:
348
+ _o = true;
349
+ return [3, 3];
350
+ case 6: return [3, 13];
351
+ case 7:
352
+ e_1_1 = _r.sent();
353
+ e_1 = { error: e_1_1 };
354
+ return [3, 13];
355
+ case 8:
356
+ _r.trys.push([8, , 11, 12]);
357
+ if (!(!_o && !_a && (_b = request_1.return))) return [3, 10];
358
+ return [4, _b.call(request_1)];
359
+ case 9:
360
+ _r.sent();
361
+ _r.label = 10;
362
+ case 10: return [3, 12];
363
+ case 11:
364
+ if (e_1) throw e_1.error;
365
+ return [7];
366
+ case 12: return [7];
367
+ case 13: return [3, 15];
368
+ case 14:
369
+ _p = _r.sent();
370
+ return [3, 15];
371
+ case 15:
372
+ parsedBody = _.attempt(function () { return Buffer.concat(chunks).toString('utf8'); });
373
+ if (!(parsedBody instanceof Error)) {
374
+ request.rawBody = parsedBody;
375
+ }
376
+ else {
377
+ request.rawBody = null;
378
+ }
379
+ _.attempt(function () { return _this.getLogger().log("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":request:body] ").concat(request.rawBody)); });
380
+ rawHandlerName = (_e = (_d = context === null || context === void 0 ? void 0 : context.getHandler) === null || _d === void 0 ? void 0 : _d.call(context)) === null || _e === void 0 ? void 0 : _e.name;
381
+ handlerPropertype = (_g = (_f = context === null || context === void 0 ? void 0 : context.getClass) === null || _f === void 0 ? void 0 : _f.call(context)) === null || _g === void 0 ? void 0 : _g.prototype;
382
+ handlerName = string_util_class_1.StringUtil.isFalsyString(request.methodName) ? rawHandlerName : request.methodName;
383
+ methodPool = getMethodPool(handlerPropertype);
384
+ authAdapters = (_h = methodPool === null || methodPool === void 0 ? void 0 : methodPool.getAuthAdapters) === null || _h === void 0 ? void 0 : _h.call(methodPool, handlerName);
385
+ if (authAdapters === null)
386
+ authAdapters = auth_adapter_decorator_1.AuthAdapters.getAdapters(handlerPropertype, handlerName);
387
+ if (!(!(sequelizeInstance instanceof Error) &&
388
+ !decorators_1.NoTransaction.isDisabled(handlerPropertype, rawHandlerName) &&
389
+ !((_j = methodPool === null || methodPool === void 0 ? void 0 : methodPool.transactionDisabled) === null || _j === void 0 ? void 0 : _j.call(methodPool, handlerName)))) return [3, 20];
390
+ _r.label = 16;
391
+ case 16:
392
+ _r.trys.push([16, 18, , 19]);
393
+ return [4, ((_l = (_k = sequelizeInstance === null || sequelizeInstance === void 0 ? void 0 : sequelizeInstance.transaction) === null || _k === void 0 ? void 0 : _k.call(sequelizeInstance)) === null || _l === void 0 ? void 0 : _l.catch(function () { return Promise.resolve(undefined); }))];
394
+ case 17:
395
+ transaction = _r.sent();
396
+ request.transaction = transaction;
397
+ this.getLogger().log("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":transaction] Started transaction for route: ").concat(handlerName));
398
+ return [3, 19];
399
+ case 18:
400
+ error_2 = _r.sent();
401
+ if (error_2 instanceof Error) {
402
+ this.getLogger().error("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":transaction] Failed to start transaction: ").concat(error_2 === null || error_2 === void 0 ? void 0 : error_2.message, "\n").concat(error_2 === null || error_2 === void 0 ? void 0 : error_2.stack));
403
+ }
404
+ return [3, 19];
405
+ case 19: return [3, 21];
406
+ case 20:
407
+ if (decorators_1.NoTransaction.isDisabled(handlerPropertype, handlerName)) {
408
+ this.getLogger().log("[trace:".concat(request === null || request === void 0 ? void 0 : request.traceId, ":transaction] Transaction is disabled for this route: ").concat(handlerName));
409
+ }
410
+ _r.label = 21;
411
+ case 21:
412
+ _r.trys.push([21, 27, , 32]);
413
+ if (!(Array.isArray(authAdapters) && authAdapters.length > 0)) return [3, 26];
414
+ _i = 0, authAdapters_1 = authAdapters;
415
+ _r.label = 22;
416
+ case 22:
417
+ if (!(_i < authAdapters_1.length)) return [3, 25];
418
+ AuthAdapterClass = authAdapters_1[_i];
419
+ adapter = new AuthAdapterClass(request, this.ref);
420
+ if (!adapter.match())
421
+ return [3, 24];
422
+ return [4, adapter.authenticate(transaction)];
423
+ case 23:
424
+ authenticateResult = _r.sent();
425
+ if (!authenticateResult)
426
+ return [3, 25];
427
+ request.authenticateResult = __assign({ AuthenticatorClass: AuthAdapterClass }, authenticateResult);
428
+ return [2, true];
429
+ case 24:
430
+ _i++;
431
+ return [3, 22];
432
+ case 25: throw new common_3.UnauthorizedException();
433
+ case 26: return [3, 32];
434
+ case 27:
435
+ error_3 = _r.sent();
436
+ _r.label = 28;
437
+ case 28:
438
+ _r.trys.push([28, 30, , 31]);
439
+ if (error_3 instanceof Error) {
440
+ this.getLogger().error("Got error when handling route: ".concat(error_3 === null || error_3 === void 0 ? void 0 : error_3.message, " ").concat(error_3 === null || error_3 === void 0 ? void 0 : error_3.stack));
441
+ }
442
+ return [4, ((_m = transaction === null || transaction === void 0 ? void 0 : transaction.rollback) === null || _m === void 0 ? void 0 : _m.call(transaction))];
443
+ case 29:
444
+ _r.sent();
445
+ return [3, 31];
446
+ case 30:
447
+ _q = _r.sent();
448
+ return [3, 31];
449
+ case 31: throw error_3;
450
+ case 32: return [2, true];
451
+ }
452
+ });
453
+ });
454
+ };
455
+ HerbalGuardMixin.prototype.getLogger = function () {
456
+ var loggerService = this.ref.get(logger_service_1.LoggerService, { strict: false });
457
+ if (!(loggerService instanceof logger_service_1.LoggerService)) {
458
+ return {
459
+ log: function () { },
460
+ error: function () { },
461
+ };
462
+ }
463
+ return loggerService;
464
+ };
465
+ HerbalGuardMixin = __decorate([
466
+ (0, common_3.Injectable)(),
467
+ __metadata("design:paramtypes", [core_1.ModuleRef])
468
+ ], HerbalGuardMixin);
469
+ return HerbalGuardMixin;
470
+ }());
471
+ return (0, common_2.mixin)(HerbalGuardMixin);
472
+ }
473
+ function getMethodPool(targetPrototype) {
474
+ var methodPool = Reflect.getMetadata(METHOD_POOL, targetPrototype);
475
+ if (!(methodPool instanceof MethodPool))
476
+ return null;
477
+ return methodPool;
478
+ }
479
+ exports.getMethodPool = getMethodPool;
480
+ var ControllerUtil = (function () {
481
+ function ControllerUtil() {
482
+ }
483
+ ControllerUtil.create = function (createOptions) {
484
+ var logger = new common_1.Logger('Herbal');
485
+ function Controller(options) {
486
+ return function (target) {
487
+ var _a;
488
+ var methodPool = new MethodPool();
489
+ var finalPrefix = string_util_class_1.StringUtil.isFalsyString(options === null || options === void 0 ? void 0 : options.prefix)
490
+ ? string_util_class_1.StringUtil.isFalsyString(createOptions === null || createOptions === void 0 ? void 0 : createOptions.prefix)
491
+ ? ''
492
+ : createOptions.prefix
493
+ : options.prefix;
494
+ var controllerName = _.camelCase(target.name.replace(/Controller$/g, ''));
495
+ var paths = [];
496
+ if (!(options === null || options === void 0 ? void 0 : options.ignoreControllerNamePostfix)) {
497
+ finalPrefix += "".concat(((_a = finalPrefix === null || finalPrefix === void 0 ? void 0 : finalPrefix.endsWith) === null || _a === void 0 ? void 0 : _a.call(finalPrefix, '/')) ? '' : '/').concat(controllerName);
498
+ }
499
+ var register = function (name, options, callback) {
500
+ if (string_util_class_1.StringUtil.isFalsyString(name) || typeof callback !== 'function')
501
+ return;
502
+ methodPool.registerMethod(name, options, callback);
503
+ paths.push(name.startsWith('/') ? name : "/".concat(name));
504
+ };
505
+ if (!finalPrefix.startsWith('/'))
506
+ finalPrefix = "/".concat(finalPrefix);
507
+ Reflect.defineMetadata(IS_HERBAL_CONTROLLER, true, target.prototype);
508
+ Reflect.defineMetadata(CONTROLLER_NAME, controllerName, target.prototype);
509
+ Reflect.defineMetadata(METHOD_POOL, methodPool, target.prototype);
510
+ if (typeof (options === null || options === void 0 ? void 0 : options.methods) === 'function')
511
+ options.methods(register);
512
+ function handleRequest(request) {
513
+ var _a, _b, _c, _d, _e, _f;
514
+ return __awaiter(this, void 0, void 0, function () {
515
+ var callFn, result, error_4;
516
+ var _g;
517
+ var _this = this;
518
+ return __generator(this, function (_h) {
519
+ switch (_h.label) {
520
+ case 0:
521
+ callFn = (_b = (_a = getMethodPool(this)) === null || _a === void 0 ? void 0 : _a.getCallFn) === null || _b === void 0 ? void 0 : _b.call(_a, request.methodName);
522
+ if (typeof callFn !== 'function')
523
+ throw new common_1.NotFoundException("Method ".concat(request.methodName, " not found"));
524
+ _h.label = 1;
525
+ case 1:
526
+ _h.trys.push([1, 4, , 6]);
527
+ _g = {};
528
+ return [4, callFn(this, {
529
+ authenticateResult: request.authenticateResult,
530
+ headers: header_util_class_1.HeaderUtil.parse((_c = request.headers) !== null && _c !== void 0 ? _c : {}),
531
+ methodName: request.methodName,
532
+ rawBody: request.rawBody,
533
+ traceId: request.traceId,
534
+ transaction: request.transaction,
535
+ url: request.originalUrl,
536
+ })];
537
+ case 2:
538
+ result = (_g.data = _h.sent(),
539
+ _g.token = string_util_class_1.StringUtil.isFalsyString((_d = request === null || request === void 0 ? void 0 : request.authenticateResult) === null || _d === void 0 ? void 0 : _d.nextToken)
540
+ ? null
541
+ : request.authenticateResult.nextToken,
542
+ _g);
543
+ return [4, ((_f = (_e = request === null || request === void 0 ? void 0 : request.transaction) === null || _e === void 0 ? void 0 : _e.commit) === null || _f === void 0 ? void 0 : _f.call(_e))];
544
+ case 3:
545
+ _h.sent();
546
+ return [2, result];
547
+ case 4:
548
+ error_4 = _h.sent();
549
+ return [4, utilities_1.AttemptUtil.execPromise((function () { return __awaiter(_this, void 0, void 0, function () {
550
+ var _a, _b;
551
+ return __generator(this, function (_c) {
552
+ switch (_c.label) {
553
+ case 0: return [4, ((_b = (_a = request === null || request === void 0 ? void 0 : request.transaction) === null || _a === void 0 ? void 0 : _a.rollback) === null || _b === void 0 ? void 0 : _b.call(_a))];
554
+ case 1:
555
+ _c.sent();
556
+ return [2];
557
+ }
558
+ });
559
+ }); })())];
560
+ case 5:
561
+ _h.sent();
562
+ throw error_4;
563
+ case 6: return [2];
564
+ }
565
+ });
566
+ });
567
+ }
568
+ Object.defineProperty(target.prototype, HANDLE_REQUEST_INSTANCE_SYMBOL, {
569
+ enumerable: false,
570
+ writable: false,
571
+ value: function (request) {
572
+ return handleRequest.call(this, request);
573
+ },
574
+ });
575
+ (0, common_1.Req)()(target.prototype, HANDLE_REQUEST_INSTANCE_SYMBOL, 0);
576
+ if (paths.length > 0) {
577
+ (0, common_2.Post)(paths)(target.prototype, HANDLE_REQUEST_INSTANCE_SYMBOL, Object.getOwnPropertyDescriptor(target.prototype, HANDLE_REQUEST_INSTANCE_SYMBOL));
578
+ paths.forEach(function (path) {
579
+ logger.log("Mapped method: /".concat(controllerName).concat(path));
580
+ });
581
+ }
582
+ (0, common_2.Controller)(finalPrefix)(target);
583
+ (0, common_2.UseInterceptors)(ControllerInterceptor)(target);
584
+ common_2.UseGuards.apply(void 0, __spreadArray(__spreadArray(__spreadArray([HerbalGuard(_.pick(createOptions, ['getTraceId']))], (Array.isArray(options === null || options === void 0 ? void 0 : options.useHeadGuards) ? options.useHeadGuards : []), false), (Array.isArray(createOptions === null || createOptions === void 0 ? void 0 : createOptions.useGuards) ? createOptions.useGuards : []), false), (Array.isArray(options === null || options === void 0 ? void 0 : options.useTailGuards) ? options.useTailGuards : []), false))(target);
585
+ };
586
+ }
587
+ Controller.isHerbalController = isHerbalController;
588
+ Controller.getControllerName = getControllerName;
589
+ return Controller;
590
+ };
591
+ return ControllerUtil;
164
592
  }());
593
+ exports.ControllerUtil = ControllerUtil;