dl-commons 0.0.1-testing.1

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 (160) hide show
  1. package/.eslintrc.js +26 -0
  2. package/.prettierrc +6 -0
  3. package/README.md +93 -0
  4. package/devops.testing.md +16 -0
  5. package/dist/constraints/is-map-of-strings.constraint.d.ts +5 -0
  6. package/dist/constraints/is-map-of-strings.constraint.js +31 -0
  7. package/dist/constraints/is-map-of-strings.constraint.js.map +1 -0
  8. package/dist/decorators/is-map-of-strings.decorator.d.ts +1 -0
  9. package/dist/decorators/is-map-of-strings.decorator.js +13 -0
  10. package/dist/decorators/is-map-of-strings.decorator.js.map +1 -0
  11. package/dist/dl-commons.module.d.ts +2 -0
  12. package/dist/dl-commons.module.js +24 -0
  13. package/dist/dl-commons.module.js.map +1 -0
  14. package/dist/exceptions/custom.exception.d.ts +11 -0
  15. package/dist/exceptions/custom.exception.js +21 -0
  16. package/dist/exceptions/custom.exception.js.map +1 -0
  17. package/dist/factories/exception.factory.d.ts +4 -0
  18. package/dist/factories/exception.factory.js +14 -0
  19. package/dist/factories/exception.factory.js.map +1 -0
  20. package/dist/filters/base-exception.filter.d.ts +8 -0
  21. package/dist/filters/base-exception.filter.js +157 -0
  22. package/dist/filters/base-exception.filter.js.map +1 -0
  23. package/dist/guards/access-token.guard.d.ts +8 -0
  24. package/dist/guards/access-token.guard.js +35 -0
  25. package/dist/guards/access-token.guard.js.map +1 -0
  26. package/dist/guards/permission.guard.d.ts +16 -0
  27. package/dist/guards/permission.guard.js +52 -0
  28. package/dist/guards/permission.guard.js.map +1 -0
  29. package/dist/index.d.ts +36 -0
  30. package/dist/index.js +76 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/models/consts/env-vars.const.d.ts +6 -0
  33. package/dist/models/consts/env-vars.const.js +10 -0
  34. package/dist/models/consts/env-vars.const.js.map +1 -0
  35. package/dist/models/dtos/commons/i18n.dto.d.ts +5 -0
  36. package/dist/models/dtos/commons/i18n.dto.js +32 -0
  37. package/dist/models/dtos/commons/i18n.dto.js.map +1 -0
  38. package/dist/models/dtos/wrappers/rest-wrapper.class.d.ts +72 -0
  39. package/dist/models/dtos/wrappers/rest-wrapper.class.js +224 -0
  40. package/dist/models/dtos/wrappers/rest-wrapper.class.js.map +1 -0
  41. package/dist/models/enums/contact-type.enum.d.ts +4 -0
  42. package/dist/models/enums/contact-type.enum.js +9 -0
  43. package/dist/models/enums/contact-type.enum.js.map +1 -0
  44. package/dist/models/enums/record-state.enum.d.ts +5 -0
  45. package/dist/models/enums/record-state.enum.js +10 -0
  46. package/dist/models/enums/record-state.enum.js.map +1 -0
  47. package/dist/models/enums/user-verifiation-level.enum.d.ts +5 -0
  48. package/dist/models/enums/user-verifiation-level.enum.js +10 -0
  49. package/dist/models/enums/user-verifiation-level.enum.js.map +1 -0
  50. package/dist/models/interfaces/base.interface.d.ts +5 -0
  51. package/dist/models/interfaces/base.interface.js +3 -0
  52. package/dist/models/interfaces/base.interface.js.map +1 -0
  53. package/dist/models/interfaces/contact.interface.d.ts +8 -0
  54. package/dist/models/interfaces/contact.interface.js +3 -0
  55. package/dist/models/interfaces/contact.interface.js.map +1 -0
  56. package/dist/models/interfaces/dictionary.interface.d.ts +9 -0
  57. package/dist/models/interfaces/dictionary.interface.js +3 -0
  58. package/dist/models/interfaces/dictionary.interface.js.map +1 -0
  59. package/dist/models/interfaces/i18n.interface.d.ts +5 -0
  60. package/dist/models/interfaces/i18n.interface.js +3 -0
  61. package/dist/models/interfaces/i18n.interface.js.map +1 -0
  62. package/dist/models/interfaces/identifable.interface.d.ts +4 -0
  63. package/dist/models/interfaces/identifable.interface.js +3 -0
  64. package/dist/models/interfaces/identifable.interface.js.map +1 -0
  65. package/dist/models/interfaces/permission.interface.d.ts +7 -0
  66. package/dist/models/interfaces/permission.interface.js +3 -0
  67. package/dist/models/interfaces/permission.interface.js.map +1 -0
  68. package/dist/models/interfaces/person.interface.d.ts +8 -0
  69. package/dist/models/interfaces/person.interface.js +3 -0
  70. package/dist/models/interfaces/person.interface.js.map +1 -0
  71. package/dist/models/interfaces/record.interface.d.ts +8 -0
  72. package/dist/models/interfaces/record.interface.js +3 -0
  73. package/dist/models/interfaces/record.interface.js.map +1 -0
  74. package/dist/models/interfaces/residence.interface.d.ts +7 -0
  75. package/dist/models/interfaces/residence.interface.js +3 -0
  76. package/dist/models/interfaces/residence.interface.js.map +1 -0
  77. package/dist/models/interfaces/role.interface.d.ts +9 -0
  78. package/dist/models/interfaces/role.interface.js +3 -0
  79. package/dist/models/interfaces/role.interface.js.map +1 -0
  80. package/dist/models/schemas/base.schema.d.ts +17 -0
  81. package/dist/models/schemas/base.schema.js +30 -0
  82. package/dist/models/schemas/base.schema.js.map +1 -0
  83. package/dist/models/schemas/embedded/contact.schema.d.ts +20 -0
  84. package/dist/models/schemas/embedded/contact.schema.js +39 -0
  85. package/dist/models/schemas/embedded/contact.schema.js.map +1 -0
  86. package/dist/models/schemas/embedded/dictionary-embedded.schema.d.ts +20 -0
  87. package/dist/models/schemas/embedded/dictionary-embedded.schema.js +40 -0
  88. package/dist/models/schemas/embedded/dictionary-embedded.schema.js.map +1 -0
  89. package/dist/models/schemas/embedded/i18n.embedded.d.ts +17 -0
  90. package/dist/models/schemas/embedded/i18n.embedded.js +33 -0
  91. package/dist/models/schemas/embedded/i18n.embedded.js.map +1 -0
  92. package/dist/models/schemas/embedded/person.schema.d.ts +20 -0
  93. package/dist/models/schemas/embedded/person.schema.js +42 -0
  94. package/dist/models/schemas/embedded/person.schema.js.map +1 -0
  95. package/dist/models/schemas/embedded/record.embedded.d.ts +20 -0
  96. package/dist/models/schemas/embedded/record.embedded.js +42 -0
  97. package/dist/models/schemas/embedded/record.embedded.js.map +1 -0
  98. package/dist/models/schemas/embedded/residence.schema.d.ts +19 -0
  99. package/dist/models/schemas/embedded/residence.schema.js +38 -0
  100. package/dist/models/schemas/embedded/residence.schema.js.map +1 -0
  101. package/dist/models/schemas/identifable.schema.d.ts +15 -0
  102. package/dist/models/schemas/identifable.schema.js +23 -0
  103. package/dist/models/schemas/identifable.schema.js.map +1 -0
  104. package/dist/pipes/mongo-id.pipe.d.ts +5 -0
  105. package/dist/pipes/mongo-id.pipe.js +21 -0
  106. package/dist/pipes/mongo-id.pipe.js.map +1 -0
  107. package/dist/pipes/mongo-ids.pipe.d.ts +5 -0
  108. package/dist/pipes/mongo-ids.pipe.js +21 -0
  109. package/dist/pipes/mongo-ids.pipe.js.map +1 -0
  110. package/dist/services/sessions.service.d.ts +3 -0
  111. package/dist/services/sessions.service.js +22 -0
  112. package/dist/services/sessions.service.js.map +1 -0
  113. package/dist/transformers/common.transformer.d.ts +8 -0
  114. package/dist/transformers/common.transformer.js +24 -0
  115. package/dist/transformers/common.transformer.js.map +1 -0
  116. package/dist/tsconfig.tsbuildinfo +1 -0
  117. package/dist/utils/helper.utils.d.ts +6 -0
  118. package/dist/utils/helper.utils.js +32 -0
  119. package/dist/utils/helper.utils.js.map +1 -0
  120. package/package.json +33 -0
  121. package/src/constraints/is-map-of-strings.constraint.ts +22 -0
  122. package/src/decorators/is-map-of-strings.decorator.ts +10 -0
  123. package/src/dl-commons.module.ts +11 -0
  124. package/src/exceptions/custom.exception.ts +20 -0
  125. package/src/factories/exception.factory.ts +14 -0
  126. package/src/filters/base-exception.filter.ts +159 -0
  127. package/src/guards/access-token.guard.ts +20 -0
  128. package/src/guards/permission.guard.ts +69 -0
  129. package/src/index.ts +174 -0
  130. package/src/models/consts/env-vars.const.ts +7 -0
  131. package/src/models/dtos/commons/i18n.dto.ts +15 -0
  132. package/src/models/dtos/wrappers/rest-wrapper.class.ts +246 -0
  133. package/src/models/enums/contact-type.enum.ts +4 -0
  134. package/src/models/enums/record-state.enum.ts +5 -0
  135. package/src/models/enums/user-verifiation-level.enum.ts +5 -0
  136. package/src/models/interfaces/base.interface.ts +6 -0
  137. package/src/models/interfaces/contact.interface.ts +9 -0
  138. package/src/models/interfaces/dictionary.interface.ts +10 -0
  139. package/src/models/interfaces/i18n.interface.ts +5 -0
  140. package/src/models/interfaces/identifable.interface.ts +5 -0
  141. package/src/models/interfaces/permission.interface.ts +8 -0
  142. package/src/models/interfaces/person.interface.ts +9 -0
  143. package/src/models/interfaces/record.interface.ts +9 -0
  144. package/src/models/interfaces/residence.interface.ts +8 -0
  145. package/src/models/interfaces/role.interface.ts +10 -0
  146. package/src/models/schemas/base.schema.ts +20 -0
  147. package/src/models/schemas/embedded/contact.schema.ts +23 -0
  148. package/src/models/schemas/embedded/dictionary-embedded.schema.ts +24 -0
  149. package/src/models/schemas/embedded/i18n.embedded.ts +18 -0
  150. package/src/models/schemas/embedded/person.schema.ts +26 -0
  151. package/src/models/schemas/embedded/record.embedded.ts +25 -0
  152. package/src/models/schemas/embedded/residence.schema.ts +23 -0
  153. package/src/models/schemas/identifable.schema.ts +11 -0
  154. package/src/pipes/mongo-id.pipe.ts +10 -0
  155. package/src/pipes/mongo-ids.pipe.ts +10 -0
  156. package/src/services/sessions.service.ts +6 -0
  157. package/src/transformers/common.transformer.ts +27 -0
  158. package/src/utils/helper.utils.ts +30 -0
  159. package/tsconfig.build.json +9 -0
  160. package/tsconfig.json +30 -0
@@ -0,0 +1,6 @@
1
+ import { Types } from 'mongoose';
2
+ declare const toStringArray: (value: string | string[]) => string[];
3
+ declare const toMongoId: (value: string) => import("bson").ObjectId;
4
+ declare const toMongoIdArray: (values: string | string[]) => Types.ObjectId[];
5
+ declare const toBoolean: (value: string) => value is "true";
6
+ export { toStringArray, toMongoId, toMongoIdArray, toBoolean };
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toBoolean = exports.toMongoIdArray = exports.toMongoId = exports.toStringArray = void 0;
4
+ const class_validator_1 = require("class-validator");
5
+ const mongoose_1 = require("mongoose");
6
+ const rest_wrapper_class_1 = require("../models/dtos/wrappers/rest-wrapper.class");
7
+ const toStringArray = (value) => {
8
+ return typeof value === 'string' ? [value] : value;
9
+ };
10
+ exports.toStringArray = toStringArray;
11
+ const toMongoId = (value) => {
12
+ const check = (0, class_validator_1.isMongoId)(value);
13
+ if (!check) {
14
+ throw new rest_wrapper_class_1.RESTError('invalid_mongoid', value);
15
+ }
16
+ return mongoose_1.Types.ObjectId.createFromHexString(value);
17
+ };
18
+ exports.toMongoId = toMongoId;
19
+ const toMongoIdArray = (values) => {
20
+ const result = [];
21
+ const items = typeof values === 'string' ? [values] : values;
22
+ for (const value of items) {
23
+ result.push(toMongoId(value));
24
+ }
25
+ return result;
26
+ };
27
+ exports.toMongoIdArray = toMongoIdArray;
28
+ const toBoolean = (value) => {
29
+ return value === 'true';
30
+ };
31
+ exports.toBoolean = toBoolean;
32
+ //# sourceMappingURL=helper.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helper.utils.js","sourceRoot":"","sources":["../../src/utils/helper.utils.ts"],"names":[],"mappings":";;;AAAA,qDAA4C;AAC5C,uCAAiC;AACjC,mFAAuE;AAEvE,MAAM,aAAa,GAAG,CAAC,KAAwB,EAAE,EAAE;IAC/C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AACvD,CAAC,CAAC;AAuBO,sCAAa;AArBtB,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,EAAE;IAChC,MAAM,KAAK,GAAG,IAAA,2BAAS,EAAC,KAAK,CAAC,CAAC;IAC/B,IAAI,CAAC,KAAK,EAAE,CAAC;QACT,MAAM,IAAI,8BAAS,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;IAClD,CAAC;IACD,OAAO,gBAAK,CAAC,QAAQ,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;AACrD,CAAC,CAAC;AAesB,8BAAS;AAbjC,MAAM,cAAc,GAAG,CAAC,MAAyB,EAAE,EAAE;IACjD,MAAM,MAAM,GAAqB,EAAE,CAAC;IACpC,MAAM,KAAK,GAAG,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC7D,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,CAAC;QACxB,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC,CAAC;AAMiC,wCAAc;AAJjD,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,EAAE;IAChC,OAAO,KAAK,KAAK,MAAM,CAAC;AAC5B,CAAC,CAAC;AAEiD,8BAAS"}
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "dl-commons",
3
+ "type": "commonjs",
4
+ "version": "0.0.1-testing.1",
5
+ "description": "distance learning commons",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "prepublish": "tsc",
10
+ "build": "tsc",
11
+ "pack": "npm run build && npm pack --pack-destination ./packs"
12
+ },
13
+ "author": "",
14
+ "license": "ISC",
15
+ "dependencies": {
16
+ "@nestjs/common": "^10.3.7",
17
+ "@nestjs/config": "^3.1.1",
18
+ "@nestjs/core": "^10.3.1",
19
+ "@nestjs/mongoose": "^10.0.2",
20
+ "class-transformer": "^0.5.1",
21
+ "class-validator": "^0.14.0",
22
+ "express": "^4.18.2",
23
+ "mongoose": "^8.0.4"
24
+ },
25
+ "devDependencies": {
26
+ "@types/express": "^4.17.17",
27
+ "@types/node": "^18.15.11",
28
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
29
+ "@typescript-eslint/parser": "^6.18.1",
30
+ "eslint": "^8.56.0",
31
+ "typescript": "^5.0.4"
32
+ }
33
+ }
@@ -0,0 +1,22 @@
1
+ import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
2
+
3
+ @ValidatorConstraint({ name: 'IsMapOfStrings', async: false })
4
+ export class IsMapOfStringsConstraint implements ValidatorConstraintInterface {
5
+ validate(value: any, args: ValidationArguments): boolean {
6
+ if (!value || typeof value !== 'object') {
7
+ return false;
8
+ }
9
+
10
+ for (let key in value) {
11
+ if (typeof value[key] !== 'string') {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ return true;
17
+ }
18
+
19
+ defaultMessage(args: ValidationArguments): string {
20
+ return `${args.property} must be a map object with string values.`;
21
+ }
22
+ }
@@ -0,0 +1,10 @@
1
+ import { Validate } from 'class-validator';
2
+ import { IsMapOfStringsConstraint } from '../constraints/is-map-of-strings.constraint';
3
+
4
+ export function IsMapOfStrings() {
5
+ return function (object: Record<string, any>, propertyName: string): void {
6
+ Validate(IsMapOfStringsConstraint, {
7
+ message: `${propertyName} must be a map object with string values.`,
8
+ })(object, propertyName);
9
+ };
10
+ }
@@ -0,0 +1,11 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { ConfigModule } from '@nestjs/config';
3
+ import { SessionsService } from './services/sessions.service';
4
+
5
+ @Module({
6
+ imports: [ConfigModule],
7
+ controllers: [],
8
+ providers: [SessionsService],
9
+ exports: [SessionsService],
10
+ })
11
+ export class DLCommonsModule {}
@@ -0,0 +1,20 @@
1
+ import { HttpException, HttpStatus } from '@nestjs/common';
2
+ import { Response } from 'express';
3
+ import { RESTError, RESTResponseBody } from '../models/dtos/wrappers/rest-wrapper.class';
4
+
5
+ class HandledException extends HttpException {
6
+ constructor(private readonly _errors: RESTError[], private readonly _statusCode?: HttpStatus) {
7
+ super({ errors: _errors }, _statusCode || HttpStatus.BAD_REQUEST);
8
+ }
9
+
10
+ public send(response: Response) {
11
+ const responseBody = RESTResponseBody.fail(this._errors, this._statusCode || HttpStatus.BAD_REQUEST);
12
+ response.status(this._statusCode).json(responseBody);
13
+ }
14
+
15
+ public getErrors() {
16
+ return this._errors;
17
+ }
18
+ }
19
+
20
+ export { HandledException };
@@ -0,0 +1,14 @@
1
+ import { HttpStatus } from '@nestjs/common';
2
+ import { ValidationError } from 'class-validator';
3
+ import { HandledException } from '../exceptions/custom.exception';
4
+ import { RESTError } from '../models/dtos/wrappers/rest-wrapper.class';
5
+
6
+ function validationExceptionFactory(_errors: ValidationError[]): HandledException {
7
+ const error = new RESTError('data_validation');
8
+ _errors.forEach((i: any) => {
9
+ error.validation = i;
10
+ });
11
+ return new HandledException([error], HttpStatus.UNPROCESSABLE_ENTITY);
12
+ }
13
+
14
+ export { validationExceptionFactory };
@@ -0,0 +1,159 @@
1
+ import {
2
+ ArgumentsHost,
3
+ BadGatewayException,
4
+ BadRequestException,
5
+ ConflictException,
6
+ ExceptionFilter,
7
+ ForbiddenException,
8
+ GatewayTimeoutException,
9
+ GoneException,
10
+ HttpStatus,
11
+ HttpVersionNotSupportedException,
12
+ ImATeapotException,
13
+ InternalServerErrorException,
14
+ MethodNotAllowedException,
15
+ NotAcceptableException,
16
+ NotFoundException,
17
+ NotImplementedException,
18
+ PayloadTooLargeException,
19
+ PreconditionFailedException,
20
+ RequestTimeoutException,
21
+ ServiceUnavailableException,
22
+ UnauthorizedException,
23
+ UnprocessableEntityException,
24
+ UnsupportedMediaTypeException,
25
+ } from '@nestjs/common';
26
+ import { mongo } from 'mongoose';
27
+ import { ValidationError } from 'class-validator';
28
+ import { HandledException } from '../exceptions/custom.exception';
29
+ import { RESTError } from '../models/dtos/wrappers/rest-wrapper.class';
30
+
31
+ export class BaseExceptionsFilter implements ExceptionFilter {
32
+ private _debug: boolean = false;
33
+ private _log: boolean = false;
34
+
35
+ constructor(debug: boolean, log?: boolean) {
36
+ this._debug = debug;
37
+ this._log = log;
38
+ }
39
+
40
+ catch(exception: any, host: ArgumentsHost) {
41
+ const context = host.switchToHttp();
42
+ const response = context.getResponse<Response>();
43
+
44
+ if (this._debug) {
45
+ console.log('BaseExceptionsFilter - name:', exception.constructor.name);
46
+ }
47
+
48
+ if (this._log) {
49
+ console.log(exception);
50
+ }
51
+
52
+ let handledException: HandledException | any = null;
53
+
54
+ const { restErrors, statusCode } = this.filterException(exception);
55
+ handledException = new HandledException(restErrors, statusCode);
56
+
57
+ handledException.send(response);
58
+ }
59
+
60
+ private filterException(exception: any) {
61
+ const restErrors: RESTError[] = [];
62
+ let statusCode: HttpStatus = null;
63
+
64
+ try {
65
+ if (exception instanceof HandledException) {
66
+ restErrors.push(...exception.getErrors());
67
+ statusCode = exception.getStatus() || HttpStatus.BAD_REQUEST;
68
+ } else if (exception instanceof RESTError) {
69
+ restErrors.push(exception);
70
+ statusCode = exception.statusCode || HttpStatus.BAD_REQUEST;
71
+ } else if (exception instanceof Array) {
72
+ exception.forEach((item) => {
73
+ restErrors.push(...this.filterException(item).restErrors);
74
+ });
75
+ statusCode = HttpStatus.BAD_REQUEST;
76
+ } else if (exception instanceof BadRequestException) {
77
+ restErrors.push(new RESTError('bad_request'));
78
+ statusCode = HttpStatus.BAD_REQUEST;
79
+ } else if (exception instanceof UnauthorizedException) {
80
+ restErrors.push(new RESTError('unauthorized'));
81
+ statusCode = HttpStatus.UNAUTHORIZED;
82
+ } else if (exception instanceof NotFoundException) {
83
+ restErrors.push(new RESTError('method_not_found', exception.message));
84
+ statusCode = HttpStatus.METHOD_NOT_ALLOWED;
85
+ } else if (exception instanceof ForbiddenException) {
86
+ restErrors.push(new RESTError('forbidden'));
87
+ statusCode = HttpStatus.FORBIDDEN;
88
+ } else if (exception instanceof NotAcceptableException) {
89
+ restErrors.push(new RESTError('NotAcceptableException'));
90
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
91
+ } else if (exception instanceof RequestTimeoutException) {
92
+ restErrors.push(new RESTError('RequestTimeoutException'));
93
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
94
+ } else if (exception instanceof ConflictException) {
95
+ restErrors.push(new RESTError('ConflictException'));
96
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
97
+ } else if (exception instanceof GoneException) {
98
+ restErrors.push(new RESTError('GoneException'));
99
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
100
+ } else if (exception instanceof HttpVersionNotSupportedException) {
101
+ restErrors.push(new RESTError('HttpVersionNotSupportedException'));
102
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
103
+ } else if (exception instanceof PayloadTooLargeException) {
104
+ restErrors.push(new RESTError('PayloadTooLargeException'));
105
+ statusCode = HttpStatus.PAYLOAD_TOO_LARGE;
106
+ } else if (exception instanceof UnsupportedMediaTypeException) {
107
+ restErrors.push(new RESTError('UnsupportedMediaTypeException'));
108
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
109
+ } else if (exception instanceof UnprocessableEntityException) {
110
+ restErrors.push(new RESTError('UnprocessableEntityException'));
111
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
112
+ } else if (exception instanceof InternalServerErrorException) {
113
+ restErrors.push(new RESTError('InternalServerErrorException'));
114
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
115
+ } else if (exception instanceof NotImplementedException) {
116
+ restErrors.push(new RESTError('NotImplementedException'));
117
+ statusCode = HttpStatus.NOT_IMPLEMENTED;
118
+ } else if (exception instanceof ImATeapotException) {
119
+ restErrors.push(new RESTError('ImATeapotException'));
120
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
121
+ } else if (exception instanceof MethodNotAllowedException) {
122
+ restErrors.push(new RESTError('MethodNotAllowedException'));
123
+ statusCode = HttpStatus.METHOD_NOT_ALLOWED;
124
+ } else if (exception instanceof BadGatewayException) {
125
+ restErrors.push(new RESTError('BadGatewayException'));
126
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
127
+ } else if (exception instanceof ServiceUnavailableException) {
128
+ restErrors.push(new RESTError('ServiceUnavailableException'));
129
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
130
+ } else if (exception instanceof GatewayTimeoutException) {
131
+ restErrors.push(new RESTError('GatewayTimeoutException'));
132
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
133
+ } else if (exception instanceof PreconditionFailedException) {
134
+ restErrors.push(new RESTError('PreconditionFailedException'));
135
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
136
+ } else if (exception instanceof TypeError) {
137
+ restErrors.push(new RESTError('type_error', exception.message));
138
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
139
+ } else if (exception instanceof mongo.MongoError) {
140
+ restErrors.push(new RESTError('mongo_error', exception.message));
141
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
142
+ } else if (exception instanceof ValidationError) {
143
+ restErrors.push(new RESTError('validation_error', exception));
144
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
145
+ } else if (exception instanceof mongo.MongoServerError) {
146
+ restErrors.push(new RESTError('mongo_server_error', exception.message));
147
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
148
+ } else {
149
+ restErrors.push(new RESTError('unknown_error', exception.message));
150
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
151
+ }
152
+ } catch (ex) {
153
+ restErrors.push(new RESTError('base_exception_filter_error', ex));
154
+ statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
155
+ }
156
+
157
+ return { restErrors, statusCode };
158
+ }
159
+ }
@@ -0,0 +1,20 @@
1
+ import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
2
+ import { ConfigService } from '@nestjs/config';
3
+ import { Observable, of } from 'rxjs';
4
+ import { APP__ACCESS_TOKEN } from '../models/consts/env-vars.const';
5
+
6
+ @Injectable()
7
+ export class AccessTokenGuard implements CanActivate {
8
+ constructor(private readonly _configService: ConfigService) {}
9
+
10
+ canActivate(context: ExecutionContext): Observable<boolean> {
11
+ const req = context.switchToHttp().getRequest();
12
+ const token = req.headers['x-access-token'];
13
+
14
+ if (!token || token !== this._configService.get<string>(APP__ACCESS_TOKEN)) {
15
+ throw new UnauthorizedException();
16
+ }
17
+
18
+ return of(true);
19
+ }
20
+ }
@@ -0,0 +1,69 @@
1
+ import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ import { Observable, of } from 'rxjs';
4
+ import { SessionsService } from '../services/sessions.service';
5
+
6
+ export class PermissionGuardArgs {
7
+ keywords?: string[] | null | undefined;
8
+ verificationLevels?: string[] | null | undefined;
9
+ }
10
+
11
+ export const AllowPermissions = Reflector.createDecorator<PermissionGuardArgs>();
12
+
13
+ @Injectable()
14
+ export class PermissionGuard implements CanActivate {
15
+ constructor(private readonly _sessionsService: SessionsService, private readonly _reflector: Reflector) {}
16
+
17
+ canActivate(context: ExecutionContext): Observable<boolean> {
18
+ const args = this._reflector.get(PermissionGuardArgs, context.getHandler());
19
+ const request = context.switchToHttp().getRequest();
20
+ const token: string = this._getToken(request);
21
+
22
+ if (!token) {
23
+ throw new UnauthorizedException();
24
+ }
25
+
26
+ console.log(args);
27
+
28
+ return of(true);
29
+ }
30
+
31
+ private _getToken(request: any) {
32
+ let token = request?.headers?.authorization;
33
+
34
+ if (!token) {
35
+ return null;
36
+ }
37
+
38
+ token = token.replace('bearer ', '');
39
+ token = token.replace('Bearer ', '');
40
+
41
+ return token;
42
+ }
43
+
44
+ /*
45
+ private _checkPermission(userPermissions: IPermission[], allowedPermission: string): boolean {
46
+ if (allowedPermission) {
47
+ return userPermissions.some((item) => item.keyword === allowedPermission);
48
+ } else {
49
+ return true;
50
+ }
51
+ }
52
+
53
+ private setUserData(userData: ISessionUserData, client: IClient, permissions: IPermission[], request: Request) {
54
+ const userInfo = {
55
+ ...userData,
56
+ client,
57
+ permissions,
58
+ };
59
+ request['user'] = userInfo;
60
+ }
61
+
62
+ private validateUserData(userData: ISessionUserData) {
63
+ if (!userData) {
64
+ throw new RESTError('unauthorized', HttpStatus.UNAUTHORIZED);
65
+ }
66
+ return userData;
67
+ }
68
+ */
69
+ }
package/src/index.ts ADDED
@@ -0,0 +1,174 @@
1
+ import { IsMapOfStrings } from './decorators/is-map-of-strings.decorator';
2
+ import { DLCommonsModule } from './dl-commons.module';
3
+ import { HandledException } from './exceptions/custom.exception';
4
+ import { validationExceptionFactory } from './factories/exception.factory';
5
+ import { BaseExceptionsFilter } from './filters/base-exception.filter';
6
+ import { AccessTokenGuard } from './guards/access-token.guard';
7
+ import { AllowPermissions, PermissionGuard } from './guards/permission.guard';
8
+ import { APP__PORT, APP__DEBUG, APP__ACCESS_TOKEN, MONGO__CS, REDIS__CS, KAFKA__BROKERS } from './models/consts/env-vars.const';
9
+ import { I18nDTO } from './models/dtos/commons/i18n.dto';
10
+ import {
11
+ IMongoPage,
12
+ RESTError,
13
+ RESTPage,
14
+ RESTPaging,
15
+ RESTQueryParams,
16
+ RESTRequestBody,
17
+ RESTResponseBody,
18
+ RESTResult,
19
+ RESTSort,
20
+ SortDirection,
21
+ } from './models/dtos/wrappers/rest-wrapper.class';
22
+ import { ContactType } from './models/enums/contact-type.enum';
23
+ import { RecordState } from './models/enums/record-state.enum';
24
+ import { UserVerificationLevel } from './models/enums/user-verifiation-level.enum';
25
+ import { IBase } from './models/interfaces/base.interface';
26
+ import { IContact } from './models/interfaces/contact.interface';
27
+ import { IDictionary } from './models/interfaces/dictionary.interface';
28
+ import { II18n } from './models/interfaces/i18n.interface';
29
+ import { IIdentifable } from './models/interfaces/identifable.interface';
30
+ import { IPermission } from './models/interfaces/permission.interface';
31
+ import { IPerson } from './models/interfaces/person.interface';
32
+ import { IRecord } from './models/interfaces/record.interface';
33
+ import { IResidence } from './models/interfaces/residence.interface';
34
+ import { IRole } from './models/interfaces/role.interface';
35
+ import { Base, BaseDocument, BaseSchema } from './models/schemas/base.schema';
36
+ import { Contact, ContactDocument, ContactSchema } from './models/schemas/embedded/contact.schema';
37
+ import { DictionaryEmbedded, DictionaryEmbeddedDocument, DictionaryEmbeddedSchema } from './models/schemas/embedded/dictionary-embedded.schema';
38
+ import { I18n, I18nSchema, I18nDocument } from './models/schemas/embedded/i18n.embedded';
39
+ import { Person, PersonSchema, PersonDocument } from './models/schemas/embedded/person.schema';
40
+ import { Record, RecordSchema, RecordDocument } from './models/schemas/embedded/record.embedded';
41
+ import { Residence, ResidenceDocument, ResidenceSchema } from './models/schemas/embedded/residence.schema';
42
+ import { Identifable, IdentifableDocument, IdentifableSchema } from './models/schemas/identifable.schema';
43
+ import { MongoIdPipe } from './pipes/mongo-id.pipe';
44
+ import { MongoIdsPipe } from './pipes/mongo-ids.pipe';
45
+ import { SessionsService } from './services/sessions.service';
46
+ import { transformers } from './transformers/common.transformer';
47
+
48
+ export {
49
+ /**
50
+ * Services
51
+ */
52
+ SessionsService,
53
+
54
+ /**
55
+ * Rest Wrapper
56
+ */
57
+ RESTError,
58
+ RESTPage,
59
+ RESTPaging,
60
+ RESTQueryParams,
61
+ RESTRequestBody,
62
+ RESTResponseBody,
63
+ RESTResult,
64
+ RESTSort,
65
+ SortDirection,
66
+ IMongoPage,
67
+
68
+ /**
69
+ * Guards
70
+ */
71
+ AccessTokenGuard,
72
+ PermissionGuard,
73
+ AllowPermissions,
74
+
75
+ /**
76
+ * Consts
77
+ */
78
+ APP__PORT,
79
+ APP__DEBUG,
80
+ APP__ACCESS_TOKEN,
81
+ MONGO__CS,
82
+ REDIS__CS,
83
+ KAFKA__BROKERS,
84
+
85
+ /**
86
+ * Enums
87
+ */
88
+ RecordState,
89
+ ContactType,
90
+ UserVerificationLevel,
91
+
92
+ /**
93
+ * DTOs
94
+ */
95
+ I18nDTO,
96
+
97
+ /**
98
+ * Interfaces
99
+ */
100
+ IIdentifable,
101
+ IBase,
102
+ IRecord,
103
+ II18n,
104
+ IDictionary,
105
+ IPermission,
106
+ IRole,
107
+ IContact,
108
+ IPerson,
109
+ IResidence,
110
+
111
+ /**
112
+ * Schemas & Documents
113
+ */
114
+ Identifable,
115
+ IdentifableSchema,
116
+ IdentifableDocument,
117
+ Base,
118
+ BaseSchema,
119
+ BaseDocument,
120
+ Record,
121
+ RecordSchema,
122
+ RecordDocument,
123
+ I18n,
124
+ I18nSchema,
125
+ I18nDocument,
126
+ Residence,
127
+ ResidenceSchema,
128
+ ResidenceDocument,
129
+ Contact,
130
+ ContactSchema,
131
+ ContactDocument,
132
+ Person,
133
+ PersonSchema,
134
+ PersonDocument,
135
+ DictionaryEmbedded,
136
+ DictionaryEmbeddedSchema,
137
+ DictionaryEmbeddedDocument,
138
+
139
+ /**
140
+ * Filters
141
+ */
142
+ BaseExceptionsFilter,
143
+
144
+ /**
145
+ * Factories
146
+ */
147
+ validationExceptionFactory,
148
+
149
+ /**
150
+ * Exceptions
151
+ */
152
+ HandledException,
153
+
154
+ /**
155
+ * Decorators
156
+ */
157
+ IsMapOfStrings,
158
+
159
+ /**
160
+ * Transformers
161
+ */
162
+ transformers,
163
+
164
+ /**
165
+ * Pipes
166
+ */
167
+ MongoIdPipe,
168
+ MongoIdsPipe,
169
+
170
+ /**
171
+ * Modules
172
+ */
173
+ DLCommonsModule,
174
+ };
@@ -0,0 +1,7 @@
1
+ export const APP__PORT = 'APP__PORT';
2
+ export const APP__DEBUG = 'APP__DEBUG';
3
+ export const APP__ACCESS_TOKEN = 'APP__ACCESS_TOKEN';
4
+
5
+ export const MONGO__CS = 'MONGO__CS';
6
+ export const REDIS__CS = 'REDIS__CS';
7
+ export const KAFKA__BROKERS = 'KAFKA__BROKERS';
@@ -0,0 +1,15 @@
1
+ import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
2
+
3
+ export class I18nDTO {
4
+ @IsString()
5
+ @IsNotEmpty()
6
+ ge: string;
7
+
8
+ @IsString()
9
+ @IsOptional()
10
+ en?: string;
11
+
12
+ @IsString()
13
+ @IsOptional()
14
+ ua?: string;
15
+ }