@nathapp/nestjs-microservices 1.0.0-rc.10

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 (60) hide show
  1. package/.eslintrc.js +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +3 -0
  4. package/dist/adapter/http-service.adapter.d.ts +10 -0
  5. package/dist/adapter/http-service.adapter.js +88 -0
  6. package/dist/adapter/index.d.ts +4 -0
  7. package/dist/adapter/index.js +7 -0
  8. package/dist/adapter/micro-service-adapter-factory.d.ts +8 -0
  9. package/dist/adapter/micro-service-adapter-factory.js +21 -0
  10. package/dist/adapter/micro-service.adapter.d.ts +19 -0
  11. package/dist/adapter/micro-service.adapter.js +2 -0
  12. package/dist/client/closeable.interface.d.ts +3 -0
  13. package/dist/client/closeable.interface.js +2 -0
  14. package/dist/client/index.d.ts +4 -0
  15. package/dist/client/index.js +7 -0
  16. package/dist/client/service-client-factory.d.ts +8 -0
  17. package/dist/client/service-client-factory.js +12 -0
  18. package/dist/client/service-client.d.ts +14 -0
  19. package/dist/client/service-client.js +14 -0
  20. package/dist/constant/index.d.ts +3 -0
  21. package/dist/constant/index.js +7 -0
  22. package/dist/constant/jwt-constant.d.ts +1 -0
  23. package/dist/constant/jwt-constant.js +4 -0
  24. package/dist/constant/module-constant.d.ts +1 -0
  25. package/dist/constant/module-constant.js +4 -0
  26. package/dist/decorator/index.d.ts +2 -0
  27. package/dist/decorator/index.js +6 -0
  28. package/dist/decorator/micro-service.decorator.d.ts +3 -0
  29. package/dist/decorator/micro-service.decorator.js +16 -0
  30. package/dist/enum/index.d.ts +2 -0
  31. package/dist/enum/index.js +5 -0
  32. package/dist/enum/transport.enum.d.ts +3 -0
  33. package/dist/enum/transport.enum.js +7 -0
  34. package/dist/guard/index.d.ts +3 -0
  35. package/dist/guard/index.js +7 -0
  36. package/dist/guard/jwt-ms-auth.guard.d.ts +11 -0
  37. package/dist/guard/jwt-ms-auth.guard.js +66 -0
  38. package/dist/guard/micro-service.guard.d.ts +11 -0
  39. package/dist/guard/micro-service.guard.js +50 -0
  40. package/dist/index.d.ts +8 -0
  41. package/dist/index.js +24 -0
  42. package/dist/module/index.d.ts +5 -0
  43. package/dist/module/index.js +11 -0
  44. package/dist/module/micro-service-clients-module-factory.d.ts +16 -0
  45. package/dist/module/micro-service-clients-module-factory.js +37 -0
  46. package/dist/module/micro-service-clients-module.interface.d.ts +27 -0
  47. package/dist/module/micro-service-clients-module.interface.js +2 -0
  48. package/dist/module/micro-service-clients.module.d.ts +11 -0
  49. package/dist/module/micro-service-clients.module.js +92 -0
  50. package/dist/module/micro-service.module.d.ts +34 -0
  51. package/dist/module/micro-service.module.js +130 -0
  52. package/dist/strategy/index.d.ts +3 -0
  53. package/dist/strategy/index.js +8 -0
  54. package/dist/strategy/microservice-jwt-strategy-provider.d.ts +13 -0
  55. package/dist/strategy/microservice-jwt-strategy-provider.js +31 -0
  56. package/dist/strategy/microservice-jwt.strategy.d.ts +9 -0
  57. package/dist/strategy/microservice-jwt.strategy.js +38 -0
  58. package/index.d.ts +1 -0
  59. package/index.js +6 -0
  60. package/package.json +57 -0
package/.eslintrc.js ADDED
@@ -0,0 +1,24 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ parserOptions: {
4
+ project: 'tsconfig.json',
5
+ sourceType: 'module',
6
+ },
7
+ plugins: ['@typescript-eslint/eslint-plugin'],
8
+ extends: [
9
+ 'plugin:@typescript-eslint/recommended',
10
+ 'plugin:prettier/recommended',
11
+ ],
12
+ root: true,
13
+ env: {
14
+ node: true,
15
+ jest: true,
16
+ },
17
+ ignorePatterns: ['.eslintrc.js'],
18
+ rules: {
19
+ '@typescript-eslint/interface-name-prefix': 'off',
20
+ '@typescript-eslint/explicit-function-return-type': 'off',
21
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
22
+ '@typescript-eslint/no-explicit-any': 'off',
23
+ },
24
+ };
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 KnowYourself
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # nestjs-micro-services Library
2
+
3
+ chatbot: 0
@@ -0,0 +1,10 @@
1
+ import { MicroServiceAdapter, HttpOption, MicroServiceRequest } from "./micro-service.adapter";
2
+ export declare class HttpServiceAdapter implements MicroServiceAdapter {
3
+ private readonly logger;
4
+ private readonly axiosClient;
5
+ private readonly options;
6
+ private readonly jwtProvider;
7
+ constructor(options: HttpOption);
8
+ execute(request: MicroServiceRequest): Promise<any>;
9
+ private isValidHttpUrl;
10
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpServiceAdapter = void 0;
4
+ const auth_1 = require("@nathapp/auth");
5
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
6
+ const common_1 = require("@nestjs/common");
7
+ const axios_1 = require("axios");
8
+ const nestjs_i18n_1 = require("nestjs-i18n");
9
+ class HttpServiceAdapter {
10
+ constructor(options) {
11
+ this.logger = new common_1.Logger(HttpServiceAdapter.name);
12
+ this.options = Object.assign({}, { option: { requestTimeout: 60000, } }, options);
13
+ const { url, requestTimeout, jwtOptions } = this.options.options;
14
+ if (jwtOptions) {
15
+ this.jwtProvider = new auth_1.JwtProvider(jwtOptions);
16
+ }
17
+ if (!this.isValidHttpUrl(url)) {
18
+ throw Error(`Invalid Url: ${url}`);
19
+ }
20
+ this.axiosClient = axios_1.default.create({
21
+ baseURL: url,
22
+ timeout: requestTimeout,
23
+ });
24
+ }
25
+ async execute(request) {
26
+ const { payload, overrides, method } = request;
27
+ const { url, requestTimeout } = this.options.options;
28
+ let bearer = this.jwtProvider ? this.jwtProvider.sign(payload || {}) : null;
29
+ let headers = {};
30
+ if (overrides && overrides.headers) {
31
+ headers = overrides.headers;
32
+ }
33
+ if (bearer) {
34
+ headers["Authorization"] = `Bearer ${bearer}`;
35
+ }
36
+ try {
37
+ const i18n = nestjs_i18n_1.I18nContext.current();
38
+ const lang = i18n === null || i18n === void 0 ? void 0 : i18n.lang;
39
+ if (!headers.hasOwnProperty("lang") && !headers.hasOwnProperty("Accept-Language") && lang) {
40
+ headers["lang"] = lang;
41
+ headers["Accept-Language"] = lang;
42
+ }
43
+ }
44
+ catch (err) {
45
+ this.logger.verbose(`I18nContext get Language Error`);
46
+ }
47
+ try {
48
+ const response = await this.axiosClient.post(method, payload, { headers });
49
+ if (!response) {
50
+ this.logger.error(`Connection Error - url: ${url},method ${method}, timeout: ${requestTimeout}`);
51
+ throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNKNOWN_ERROR);
52
+ }
53
+ if (200 != response.status && 201 != response.status) {
54
+ this.logger.error(`Invalid response - status: ${response.status}, url: ${url},method ${method}, timeout: ${requestTimeout}`);
55
+ throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNKNOWN_ERROR);
56
+ }
57
+ const result = response.data;
58
+ if ("0" != result.ret) {
59
+ this.logger.error(`Failed response - ret: ${result.ret}, url: ${url},method ${method}, timeout: ${requestTimeout}`);
60
+ this.logger.error(`Failed response message: ${result.msg || result.message}`);
61
+ if (result.ret) {
62
+ throw new nestjs_common_1.HttpMicroServiceException(result.ret, result.msg || result.message);
63
+ }
64
+ else {
65
+ throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNKNOWN_ERROR);
66
+ }
67
+ }
68
+ return result.data;
69
+ }
70
+ catch (error) {
71
+ if (!(error instanceof nestjs_common_1.AppException)) {
72
+ this.logger.error(`Unknown Exception Error - url: ${url},method ${method}, timeout: ${requestTimeout}`);
73
+ }
74
+ this.logger.error(error);
75
+ throw error;
76
+ }
77
+ }
78
+ isValidHttpUrl(url) {
79
+ try {
80
+ const newUrl = new URL(url);
81
+ return newUrl.protocol === 'http:' || newUrl.protocol === 'https:';
82
+ }
83
+ catch (err) {
84
+ return false;
85
+ }
86
+ }
87
+ }
88
+ exports.HttpServiceAdapter = HttpServiceAdapter;
@@ -0,0 +1,4 @@
1
+ import { HttpServiceAdapter } from "./http-service.adapter";
2
+ import { MicroServiceAdapterFactory } from "./micro-service-adapter-factory";
3
+ import { MicroServiceAdapter, HttpOption, MicroServiceRequest } from "./micro-service.adapter";
4
+ export { MicroServiceAdapter, HttpServiceAdapter, HttpOption, MicroServiceRequest, MicroServiceAdapterFactory };
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MicroServiceAdapterFactory = exports.HttpServiceAdapter = void 0;
4
+ const http_service_adapter_1 = require("./http-service.adapter");
5
+ Object.defineProperty(exports, "HttpServiceAdapter", { enumerable: true, get: function () { return http_service_adapter_1.HttpServiceAdapter; } });
6
+ const micro_service_adapter_factory_1 = require("./micro-service-adapter-factory");
7
+ Object.defineProperty(exports, "MicroServiceAdapterFactory", { enumerable: true, get: function () { return micro_service_adapter_factory_1.MicroServiceAdapterFactory; } });
@@ -0,0 +1,8 @@
1
+ import { HttpServiceAdapter, MicroServiceAdapter } from ".";
2
+ import { ServiceClientOptions } from "../client";
3
+ export interface IMicroServiceAdapterFactory {
4
+ createAdapter(clientOptions: ServiceClientOptions): HttpServiceAdapter;
5
+ }
6
+ export declare class MicroServiceAdapterFactory {
7
+ static createAdapter(clientOptions: ServiceClientOptions): MicroServiceAdapter;
8
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MicroServiceAdapterFactory = void 0;
4
+ const _1 = require(".");
5
+ const enum_1 = require("../enum");
6
+ class MicroServiceAdapterFactory {
7
+ static createAdapter(clientOptions) {
8
+ const { transport } = clientOptions || {};
9
+ let adapter;
10
+ switch (transport) {
11
+ case enum_1.Transport.HTTP:
12
+ adapter = new _1.HttpServiceAdapter(clientOptions);
13
+ break;
14
+ default:
15
+ adapter = new _1.HttpServiceAdapter(clientOptions);
16
+ break;
17
+ }
18
+ return adapter;
19
+ }
20
+ }
21
+ exports.MicroServiceAdapterFactory = MicroServiceAdapterFactory;
@@ -0,0 +1,19 @@
1
+ import { JwtOptions } from "@nathapp/auth";
2
+ import { Transport } from "../enum";
3
+ export interface HttpOption {
4
+ transport: Transport.HTTP;
5
+ options: {
6
+ url: string;
7
+ jwtOptions?: JwtOptions;
8
+ requestTimeout?: number;
9
+ };
10
+ }
11
+ export interface MicroServiceRequest {
12
+ method: string;
13
+ payload?: any;
14
+ overrides?: any;
15
+ version?: string;
16
+ }
17
+ export interface MicroServiceAdapter {
18
+ execute(request: MicroServiceRequest): Promise<any>;
19
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,3 @@
1
+ export interface Closeable {
2
+ close(): void;
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import { Closeable } from "./closeable.interface";
2
+ import { ServiceClient, DefaultServiceClient, ServiceClientOptions, AuthenticateOptions } from "./service-client";
3
+ import { IServiceClientFactory, ServiceClientFactory } from "./service-client-factory";
4
+ export { ServiceClientOptions, AuthenticateOptions, ServiceClient, DefaultServiceClient, Closeable, IServiceClientFactory, ServiceClientFactory, };
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ServiceClientFactory = exports.DefaultServiceClient = void 0;
4
+ const service_client_1 = require("./service-client");
5
+ Object.defineProperty(exports, "DefaultServiceClient", { enumerable: true, get: function () { return service_client_1.DefaultServiceClient; } });
6
+ const service_client_factory_1 = require("./service-client-factory");
7
+ Object.defineProperty(exports, "ServiceClientFactory", { enumerable: true, get: function () { return service_client_factory_1.ServiceClientFactory; } });
@@ -0,0 +1,8 @@
1
+ import { Closeable } from "./closeable.interface";
2
+ import { AuthenticateOptions, ServiceClient, ServiceClientOptions } from "./service-client";
3
+ export interface IServiceClientFactory {
4
+ create(clientOptions: ServiceClientOptions, authOptions: AuthenticateOptions): ServiceClient & Closeable;
5
+ }
6
+ export declare class ServiceClientFactory {
7
+ static create(clientOptions: ServiceClientOptions): ServiceClient & Closeable;
8
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ServiceClientFactory = void 0;
4
+ const adapter_1 = require("../adapter");
5
+ const service_client_1 = require("./service-client");
6
+ class ServiceClientFactory {
7
+ static create(clientOptions) {
8
+ const adapter = adapter_1.MicroServiceAdapterFactory.createAdapter(clientOptions);
9
+ return new service_client_1.DefaultServiceClient(adapter);
10
+ }
11
+ }
12
+ exports.ServiceClientFactory = ServiceClientFactory;
@@ -0,0 +1,14 @@
1
+ import { JwtOptions } from "@nathapp/auth";
2
+ import { HttpOption, MicroServiceAdapter, MicroServiceRequest } from "../adapter";
3
+ import { Closeable } from "./closeable.interface";
4
+ export type AuthenticateOptions = JwtOptions;
5
+ export type ServiceClientOptions = HttpOption;
6
+ export interface ServiceClient {
7
+ execute(request: MicroServiceRequest): Promise<any>;
8
+ }
9
+ export declare class DefaultServiceClient implements ServiceClient, Closeable {
10
+ private readonly adapter;
11
+ constructor(adapter: MicroServiceAdapter);
12
+ close(): void;
13
+ execute(request: MicroServiceRequest): Promise<any>;
14
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultServiceClient = void 0;
4
+ class DefaultServiceClient {
5
+ constructor(adapter) {
6
+ this.adapter = adapter;
7
+ }
8
+ close() {
9
+ }
10
+ execute(request) {
11
+ return this.adapter.execute(request);
12
+ }
13
+ }
14
+ exports.DefaultServiceClient = DefaultServiceClient;
@@ -0,0 +1,3 @@
1
+ import { MICROSERVICE_STRATEGY_NAME } from "./jwt-constant";
2
+ import { MICROSERVICE_OPTIONS } from "./module-constant";
3
+ export { MICROSERVICE_STRATEGY_NAME, MICROSERVICE_OPTIONS, };
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MICROSERVICE_OPTIONS = exports.MICROSERVICE_STRATEGY_NAME = void 0;
4
+ const jwt_constant_1 = require("./jwt-constant");
5
+ Object.defineProperty(exports, "MICROSERVICE_STRATEGY_NAME", { enumerable: true, get: function () { return jwt_constant_1.MICROSERVICE_STRATEGY_NAME; } });
6
+ const module_constant_1 = require("./module-constant");
7
+ Object.defineProperty(exports, "MICROSERVICE_OPTIONS", { enumerable: true, get: function () { return module_constant_1.MICROSERVICE_OPTIONS; } });
@@ -0,0 +1 @@
1
+ export declare const MICROSERVICE_STRATEGY_NAME = "MICROSERVICE-JWT";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MICROSERVICE_STRATEGY_NAME = void 0;
4
+ exports.MICROSERVICE_STRATEGY_NAME = "MICROSERVICE-JWT";
@@ -0,0 +1 @@
1
+ export declare const MICROSERVICE_OPTIONS = "MICROSERVICE_OPTIONS";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MICROSERVICE_OPTIONS = void 0;
4
+ exports.MICROSERVICE_OPTIONS = "MICROSERVICE_OPTIONS";
@@ -0,0 +1,2 @@
1
+ import { MICRO_SERVICES_KEY, MsServices } from "./micro-service.decorator";
2
+ export { MICRO_SERVICES_KEY, MsServices };
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MsServices = exports.MICRO_SERVICES_KEY = void 0;
4
+ const micro_service_decorator_1 = require("./micro-service.decorator");
5
+ Object.defineProperty(exports, "MICRO_SERVICES_KEY", { enumerable: true, get: function () { return micro_service_decorator_1.MICRO_SERVICES_KEY; } });
6
+ Object.defineProperty(exports, "MsServices", { enumerable: true, get: function () { return micro_service_decorator_1.MsServices; } });
@@ -0,0 +1,3 @@
1
+ export declare const MICRO_SERVICES_KEY = "MicroServices";
2
+ export declare const MsServices: (method?: string | string[]) => <TFunction extends Function, Y>(target: object | TFunction, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
3
+ export declare const MsPayload: (...dataOrPipes: unknown[]) => ParameterDecorator;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MsPayload = exports.MsServices = exports.MICRO_SERVICES_KEY = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const common_2 = require("@nestjs/common");
6
+ const guard_1 = require("../guard");
7
+ exports.MICRO_SERVICES_KEY = "MicroServices";
8
+ const MsServices = (method) => {
9
+ return (0, common_1.applyDecorators)((0, common_1.SetMetadata)(exports.MICRO_SERVICES_KEY, true), (0, common_1.UseGuards)(guard_1.MicroServiceJwtAuthGuard), (0, common_1.Post)(method));
10
+ };
11
+ exports.MsServices = MsServices;
12
+ exports.MsPayload = (0, common_2.createParamDecorator)((data, ctx) => {
13
+ const request = ctx.switchToHttp().getRequest();
14
+ const user = request.user;
15
+ return user ? request.body : {};
16
+ });
@@ -0,0 +1,2 @@
1
+ import { Transport } from "./transport.enum";
2
+ export { Transport, };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = void 0;
4
+ const transport_enum_1 = require("./transport.enum");
5
+ Object.defineProperty(exports, "Transport", { enumerable: true, get: function () { return transport_enum_1.Transport; } });
@@ -0,0 +1,3 @@
1
+ export declare enum Transport {
2
+ HTTP = 0
3
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = void 0;
4
+ var Transport;
5
+ (function (Transport) {
6
+ Transport[Transport["HTTP"] = 0] = "HTTP";
7
+ })(Transport = exports.Transport || (exports.Transport = {}));
@@ -0,0 +1,3 @@
1
+ import { JwtMsAuthGuard } from "./jwt-ms-auth.guard";
2
+ import { MicroServiceJwtAuthGuard } from "./micro-service.guard";
3
+ export { JwtMsAuthGuard, MicroServiceJwtAuthGuard, };
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MicroServiceJwtAuthGuard = exports.JwtMsAuthGuard = void 0;
4
+ const jwt_ms_auth_guard_1 = require("./jwt-ms-auth.guard");
5
+ Object.defineProperty(exports, "JwtMsAuthGuard", { enumerable: true, get: function () { return jwt_ms_auth_guard_1.JwtMsAuthGuard; } });
6
+ const micro_service_guard_1 = require("./micro-service.guard");
7
+ Object.defineProperty(exports, "MicroServiceJwtAuthGuard", { enumerable: true, get: function () { return micro_service_guard_1.MicroServiceJwtAuthGuard; } });
@@ -0,0 +1,11 @@
1
+ import { ExecutionContext } from "@nestjs/common";
2
+ import { Reflector } from "@nestjs/core";
3
+ declare const JwtMsAuthGuard_base: import("@nestjs/passport").Type<import("@nestjs/passport").IAuthGuard>;
4
+ export declare class JwtMsAuthGuard extends JwtMsAuthGuard_base {
5
+ private reflector;
6
+ private readonly logger;
7
+ constructor(reflector: Reflector);
8
+ canActivate(context: ExecutionContext): boolean | Promise<boolean> | import("rxjs").Observable<boolean>;
9
+ handleRequest(err: any, user: any, info: any): any;
10
+ }
11
+ export {};
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var JwtMsAuthGuard_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.JwtMsAuthGuard = void 0;
14
+ const nestjs_auth_1 = require("@nathapp/nestjs-auth");
15
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
16
+ const common_1 = require("@nestjs/common");
17
+ const core_1 = require("@nestjs/core");
18
+ const passport_1 = require("@nestjs/passport");
19
+ const decorator_1 = require("../decorator");
20
+ let JwtMsAuthGuard = JwtMsAuthGuard_1 = class JwtMsAuthGuard extends (0, passport_1.AuthGuard)(nestjs_auth_1.JWT_STRATEGY_NAME) {
21
+ constructor(reflector) {
22
+ super();
23
+ this.reflector = reflector;
24
+ this.logger = new common_1.Logger(JwtMsAuthGuard_1.name);
25
+ }
26
+ canActivate(context) {
27
+ const handler = context.getHandler();
28
+ const clazz = context.getClass();
29
+ const isPublic = this.reflector.getAllAndOverride(nestjs_auth_1.IS_PUBLIC_KEY, [
30
+ handler,
31
+ clazz,
32
+ ]);
33
+ const RefreshToken = this.reflector.getAllAndOverride(nestjs_auth_1.REFRESH_TOKEN, [
34
+ handler,
35
+ clazz,
36
+ ]);
37
+ const IsMicroServiceProtected = this.reflector.getAllAndOverride(decorator_1.MICRO_SERVICES_KEY, [
38
+ handler,
39
+ clazz,
40
+ ]);
41
+ if (isPublic) {
42
+ this.logger.verbose(`has isPublic decorator, class: ${clazz.name}, method: ${handler.name}`);
43
+ return true;
44
+ }
45
+ if (RefreshToken) {
46
+ this.logger.verbose(`has RefreshToken decorator, class: ${clazz.name}, method: ${handler.name}`);
47
+ return true;
48
+ }
49
+ if (IsMicroServiceProtected) {
50
+ this.logger.verbose(`has MsProtected decorator, class: ${clazz.name}, method: ${handler.name}`);
51
+ return true;
52
+ }
53
+ return super.canActivate(context);
54
+ }
55
+ handleRequest(err, user, info) {
56
+ if (err || !user) {
57
+ throw err || new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
58
+ }
59
+ return user;
60
+ }
61
+ };
62
+ JwtMsAuthGuard = JwtMsAuthGuard_1 = __decorate([
63
+ (0, common_1.Injectable)(),
64
+ __metadata("design:paramtypes", [core_1.Reflector])
65
+ ], JwtMsAuthGuard);
66
+ exports.JwtMsAuthGuard = JwtMsAuthGuard;
@@ -0,0 +1,11 @@
1
+ import { ExecutionContext } from "@nestjs/common";
2
+ import { Reflector } from "@nestjs/core";
3
+ declare const MicroServiceJwtAuthGuard_base: import("@nestjs/passport").Type<import("@nestjs/passport").IAuthGuard>;
4
+ export declare class MicroServiceJwtAuthGuard extends MicroServiceJwtAuthGuard_base {
5
+ private reflector;
6
+ private readonly logger;
7
+ constructor(reflector: Reflector);
8
+ canActivate(context: ExecutionContext): boolean | Promise<boolean> | import("rxjs").Observable<boolean>;
9
+ handleRequest(err: any, user: any, info: any): any;
10
+ }
11
+ export {};
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var MicroServiceJwtAuthGuard_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.MicroServiceJwtAuthGuard = void 0;
14
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
15
+ const common_1 = require("@nestjs/common");
16
+ const core_1 = require("@nestjs/core");
17
+ const passport_1 = require("@nestjs/passport");
18
+ const constant_1 = require("../constant");
19
+ const decorator_1 = require("../decorator");
20
+ let MicroServiceJwtAuthGuard = MicroServiceJwtAuthGuard_1 = class MicroServiceJwtAuthGuard extends (0, passport_1.AuthGuard)(constant_1.MICROSERVICE_STRATEGY_NAME) {
21
+ constructor(reflector) {
22
+ super();
23
+ this.reflector = reflector;
24
+ this.logger = new common_1.Logger(MicroServiceJwtAuthGuard_1.name);
25
+ }
26
+ canActivate(context) {
27
+ const handler = context.getHandler();
28
+ const clazz = context.getClass();
29
+ const isMicroServices = this.reflector.getAllAndOverride(decorator_1.MICRO_SERVICES_KEY, [
30
+ handler,
31
+ clazz,
32
+ ]);
33
+ if (!isMicroServices) {
34
+ this.logger.verbose(`is not isMicroServices decorator, class: ${clazz.name}, method: ${handler.name}`);
35
+ return true;
36
+ }
37
+ return super.canActivate(context);
38
+ }
39
+ handleRequest(err, user, info) {
40
+ if (err || !user) {
41
+ throw err || new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
42
+ }
43
+ return user;
44
+ }
45
+ };
46
+ MicroServiceJwtAuthGuard = MicroServiceJwtAuthGuard_1 = __decorate([
47
+ (0, common_1.Injectable)(),
48
+ __metadata("design:paramtypes", [core_1.Reflector])
49
+ ], MicroServiceJwtAuthGuard);
50
+ exports.MicroServiceJwtAuthGuard = MicroServiceJwtAuthGuard;
@@ -0,0 +1,8 @@
1
+ export * from "./adapter";
2
+ export * from "./client";
3
+ export * from './constant';
4
+ export * from './decorator';
5
+ export * from "./enum";
6
+ export * from "./guard";
7
+ export * from './module';
8
+ export * from './strategy';
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./adapter"), exports);
18
+ __exportStar(require("./client"), exports);
19
+ __exportStar(require("./constant"), exports);
20
+ __exportStar(require("./decorator"), exports);
21
+ __exportStar(require("./enum"), exports);
22
+ __exportStar(require("./guard"), exports);
23
+ __exportStar(require("./module"), exports);
24
+ __exportStar(require("./strategy"), exports);
@@ -0,0 +1,5 @@
1
+ import { HttpClientsModuleOptionsFactory, JwtClientsModuleOptionsFactory } from "./micro-service-clients-module-factory";
2
+ import { ServiceClientProvider, ServiceClientProviderOptions, ClientsModuleOptions, ClientsModuleOptionsFactory, ServiceClientsProviderAsyncOptions, ClientsModuleAsyncOptions } from "./micro-service-clients-module.interface";
3
+ import { MicroServiceClientsModule } from "./micro-service-clients.module";
4
+ import { DefaultMicroServiceModuleOptionsFactory, MicroServiceModule, MicroServiceModuleOptionsFactory } from "./micro-service.module";
5
+ export { MicroServiceModule, ServiceClientProvider, ServiceClientProviderOptions, ClientsModuleOptions, ClientsModuleOptionsFactory, ServiceClientsProviderAsyncOptions, ClientsModuleAsyncOptions, JwtClientsModuleOptionsFactory, HttpClientsModuleOptionsFactory, MicroServiceModuleOptionsFactory, DefaultMicroServiceModuleOptionsFactory, MicroServiceClientsModule, };
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MicroServiceClientsModule = exports.DefaultMicroServiceModuleOptionsFactory = exports.HttpClientsModuleOptionsFactory = exports.JwtClientsModuleOptionsFactory = exports.MicroServiceModule = void 0;
4
+ const micro_service_clients_module_factory_1 = require("./micro-service-clients-module-factory");
5
+ Object.defineProperty(exports, "HttpClientsModuleOptionsFactory", { enumerable: true, get: function () { return micro_service_clients_module_factory_1.HttpClientsModuleOptionsFactory; } });
6
+ Object.defineProperty(exports, "JwtClientsModuleOptionsFactory", { enumerable: true, get: function () { return micro_service_clients_module_factory_1.JwtClientsModuleOptionsFactory; } });
7
+ const micro_service_clients_module_1 = require("./micro-service-clients.module");
8
+ Object.defineProperty(exports, "MicroServiceClientsModule", { enumerable: true, get: function () { return micro_service_clients_module_1.MicroServiceClientsModule; } });
9
+ const micro_service_module_1 = require("./micro-service.module");
10
+ Object.defineProperty(exports, "DefaultMicroServiceModuleOptionsFactory", { enumerable: true, get: function () { return micro_service_module_1.DefaultMicroServiceModuleOptionsFactory; } });
11
+ Object.defineProperty(exports, "MicroServiceModule", { enumerable: true, get: function () { return micro_service_module_1.MicroServiceModule; } });
@@ -0,0 +1,16 @@
1
+ import { JwtOptions } from "@nathapp/auth";
2
+ import { ClientsModuleOptionsFactory, ServiceClientProvider } from ".";
3
+ import { HttpOption } from "../adapter";
4
+ export declare abstract class JwtClientsModuleOptionsFactory implements ClientsModuleOptionsFactory {
5
+ createClientOptions(): Promise<ServiceClientProvider> | ServiceClientProvider;
6
+ protected abstract createJwtMicroServiceOptions(jwtOption: JwtOptions): Promise<ServiceClientProvider> | ServiceClientProvider;
7
+ protected createJwtOptions(): JwtOptions;
8
+ }
9
+ export declare class HttpClientsModuleOptionsFactory extends JwtClientsModuleOptionsFactory {
10
+ private readonly options;
11
+ constructor(options: {
12
+ url: string;
13
+ requestTimeout?: number;
14
+ });
15
+ protected createJwtMicroServiceOptions(jwtOption: JwtOptions): HttpOption | Promise<HttpOption>;
16
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpClientsModuleOptionsFactory = exports.JwtClientsModuleOptionsFactory = void 0;
4
+ const enum_1 = require("../enum");
5
+ class JwtClientsModuleOptionsFactory {
6
+ createClientOptions() {
7
+ return this.createJwtMicroServiceOptions(this.createJwtOptions());
8
+ }
9
+ createJwtOptions() {
10
+ return {
11
+ secret: process.env.MS_JWT_ACCESS_SECRET,
12
+ publicKey: process.env.MS_JWT_ACCESS_PUBLICKEY,
13
+ privateKey: process.env.MS_JWT_ACCESS_PRIVATEKEY,
14
+ passphrase: process.env.MS_JWT_ACCESS_PASSPHRASE,
15
+ signOption: {
16
+ expiresIn: process.env.MS_JWT_ACCESS_EXPIRE,
17
+ algorithm: process.env.MS_JWT_ACCESS_ALGORITHM,
18
+ },
19
+ };
20
+ }
21
+ }
22
+ exports.JwtClientsModuleOptionsFactory = JwtClientsModuleOptionsFactory;
23
+ class HttpClientsModuleOptionsFactory extends JwtClientsModuleOptionsFactory {
24
+ constructor(options) {
25
+ super();
26
+ options = Object.assign({ requestTimeout: 60000 }, options);
27
+ this.options = {
28
+ transport: enum_1.Transport.HTTP,
29
+ options,
30
+ };
31
+ }
32
+ createJwtMicroServiceOptions(jwtOption) {
33
+ this.options.options.jwtOptions = jwtOption;
34
+ return this.options;
35
+ }
36
+ }
37
+ exports.HttpClientsModuleOptionsFactory = HttpClientsModuleOptionsFactory;
@@ -0,0 +1,27 @@
1
+ import { Type, Provider, ModuleMetadata } from '@nestjs/common/interfaces';
2
+ import { ServiceClientOptions } from '../client';
3
+ export type ServiceClientProvider = ServiceClientOptions;
4
+ export type ServiceClientProviderOptions = ServiceClientProvider & {
5
+ name: string | symbol;
6
+ };
7
+ export type ClientsModuleOptions = {
8
+ name?: string;
9
+ clients: Array<ServiceClientProviderOptions>;
10
+ isGlobal?: boolean;
11
+ };
12
+ export interface ClientsModuleOptionsFactory {
13
+ createClientOptions(): Promise<ServiceClientProvider> | ServiceClientProvider;
14
+ }
15
+ export interface ServiceClientsProviderAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
16
+ useExisting?: Type<ClientsModuleOptionsFactory>;
17
+ useClass?: Type<ClientsModuleOptionsFactory>;
18
+ useFactory?: (...args: any[]) => Promise<ServiceClientProvider> | ServiceClientProvider;
19
+ inject?: any[];
20
+ extraProviders?: Provider[];
21
+ name: string | symbol;
22
+ }
23
+ export type ClientsModuleAsyncOptions = {
24
+ name?: string;
25
+ clients: Array<ServiceClientsProviderAsyncOptions>;
26
+ isGlobal?: boolean;
27
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,11 @@
1
+ import { DynamicModule } from '@nestjs/common';
2
+ import { ClientsModuleAsyncOptions, ClientsModuleOptions } from '.';
3
+ export declare class MicroServiceClientsModule {
4
+ static register(options: ClientsModuleOptions): DynamicModule;
5
+ static registerAsync(options: ClientsModuleAsyncOptions): DynamicModule;
6
+ private static sanitizeModuleOptions;
7
+ private static createAsyncProviders;
8
+ private static createAsyncOptionsProvider;
9
+ private static createFactoryWrapper;
10
+ private static assignOnAppShutdownHook;
11
+ }
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var MicroServiceClientsModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.MicroServiceClientsModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const client_1 = require("../client");
13
+ const defaultOptions = {};
14
+ let MicroServiceClientsModule = MicroServiceClientsModule_1 = class MicroServiceClientsModule {
15
+ static register(options) {
16
+ options = this.sanitizeModuleOptions(options);
17
+ const clientsOptions = options.clients;
18
+ const clients = (clientsOptions || []).map(item => ({
19
+ provide: item.name,
20
+ useValue: this.assignOnAppShutdownHook(client_1.ServiceClientFactory.create(item)),
21
+ }));
22
+ return {
23
+ module: MicroServiceClientsModule_1,
24
+ global: options.isGlobal,
25
+ providers: clients,
26
+ exports: clients,
27
+ };
28
+ }
29
+ static registerAsync(options) {
30
+ options = this.sanitizeModuleOptions(options);
31
+ const clientsOptions = options.clients;
32
+ const providers = clientsOptions.reduce((accProviders, item) => accProviders
33
+ .concat(this.createAsyncProviders(item))
34
+ .concat(item.extraProviders || []), []);
35
+ const imports = clientsOptions.reduce((accImports, option) => option.imports && !accImports.includes(option.imports)
36
+ ? accImports.concat(option.imports)
37
+ : accImports, []);
38
+ return {
39
+ module: MicroServiceClientsModule_1,
40
+ global: options.isGlobal,
41
+ imports,
42
+ providers: providers,
43
+ exports: providers,
44
+ };
45
+ }
46
+ static sanitizeModuleOptions(options) {
47
+ options = { ...defaultOptions, ...options };
48
+ return options;
49
+ }
50
+ static createAsyncProviders(options) {
51
+ if (options.useExisting || options.useFactory) {
52
+ return [this.createAsyncOptionsProvider(options)];
53
+ }
54
+ return [
55
+ this.createAsyncOptionsProvider(options),
56
+ {
57
+ provide: options.useClass,
58
+ useClass: options.useClass,
59
+ },
60
+ ];
61
+ }
62
+ static createAsyncOptionsProvider(options) {
63
+ if (options.useFactory) {
64
+ return {
65
+ provide: options.name,
66
+ useFactory: this.createFactoryWrapper(options.useFactory),
67
+ inject: options.inject || [],
68
+ };
69
+ }
70
+ return {
71
+ provide: options.name,
72
+ useFactory: this.createFactoryWrapper((optionsFactory) => optionsFactory.createClientOptions()),
73
+ inject: [options.useExisting || options.useClass],
74
+ };
75
+ }
76
+ static createFactoryWrapper(useFactory) {
77
+ return async (...args) => {
78
+ const clientOptions = await useFactory(...args);
79
+ const clientProxyRef = client_1.ServiceClientFactory.create(clientOptions);
80
+ return this.assignOnAppShutdownHook(clientProxyRef);
81
+ };
82
+ }
83
+ static assignOnAppShutdownHook(client) {
84
+ client.onApplicationShutdown =
85
+ client.close;
86
+ return client;
87
+ }
88
+ };
89
+ MicroServiceClientsModule = MicroServiceClientsModule_1 = __decorate([
90
+ (0, common_1.Module)({})
91
+ ], MicroServiceClientsModule);
92
+ exports.MicroServiceClientsModule = MicroServiceClientsModule;
@@ -0,0 +1,34 @@
1
+ import { DynamicModule, ModuleMetadata, Type } from '@nestjs/common';
2
+ import { JwtOptions, StrategyProvider } from '@nathapp/nestjs-auth';
3
+ export declare class MicroServiceModule {
4
+ static register(options: MicroServiceModuleOptions): DynamicModule;
5
+ static registerAsync(options: MicroServiceModuleAsyncOptions): DynamicModule;
6
+ private static sanitizeMSModuleOptions;
7
+ private static createStrategyProvider;
8
+ private static createAsyncOptionsProviders;
9
+ private static createAsyncOptionsProvider;
10
+ }
11
+ export type MicroServiceModuleOptionsWithoutProvider = Omit<MicroServiceModuleOptions, 'strategyProvider'>;
12
+ export type MicroServiceOption = JwtOptions;
13
+ export interface MicroServiceModuleOptions {
14
+ name?: string;
15
+ options: MicroServiceOption;
16
+ logging?: boolean;
17
+ strategyProvider?: Type<StrategyProvider>;
18
+ }
19
+ export interface MicroServiceModuleOptionsFactory {
20
+ createOptions(): Promise<MicroServiceModuleOptionsWithoutProvider> | MicroServiceModuleOptionsWithoutProvider;
21
+ }
22
+ export interface MicroServiceModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
23
+ name?: string;
24
+ useExisting?: Type<MicroServiceModuleOptionsFactory>;
25
+ useClass?: Type<MicroServiceModuleOptionsFactory>;
26
+ useFactory?: (...args: any[]) => MicroServiceModuleOptionsWithoutProvider | Promise<MicroServiceModuleOptionsWithoutProvider>;
27
+ strategyProvider?: Type<StrategyProvider>;
28
+ inject?: any[];
29
+ }
30
+ export declare class DefaultMicroServiceModuleOptionsFactory implements MicroServiceModuleOptionsFactory {
31
+ private readonly extraOptions;
32
+ constructor();
33
+ createOptions(): MicroServiceModuleOptionsWithoutProvider | Promise<MicroServiceModuleOptionsWithoutProvider>;
34
+ }
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var MicroServiceModule_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.DefaultMicroServiceModuleOptionsFactory = exports.MicroServiceModule = void 0;
14
+ const common_1 = require("@nestjs/common");
15
+ const constant_1 = require("../constant");
16
+ const strategy_1 = require("../strategy");
17
+ const defaultOptions = {
18
+ logging: true,
19
+ };
20
+ let MicroServiceModule = MicroServiceModule_1 = class MicroServiceModule {
21
+ static register(options) {
22
+ options = this.sanitizeMSModuleOptions(options);
23
+ const msOptions = {
24
+ provide: constant_1.MICROSERVICE_OPTIONS,
25
+ useValue: options,
26
+ };
27
+ const strategyProvider = this.createStrategyProvider(options);
28
+ return {
29
+ module: MicroServiceModule_1,
30
+ imports: [],
31
+ providers: [msOptions, strategyProvider],
32
+ exports: [constant_1.MICROSERVICE_OPTIONS, strategyProvider],
33
+ };
34
+ }
35
+ static registerAsync(options) {
36
+ options = this.sanitizeMSModuleOptions(options);
37
+ const asyncOptionsProviders = this.createAsyncOptionsProviders(options);
38
+ const strategyProvider = this.createStrategyProvider(options);
39
+ return {
40
+ module: MicroServiceModule_1,
41
+ imports: options.imports || [],
42
+ providers: [...asyncOptionsProviders, strategyProvider],
43
+ exports: [constant_1.MICROSERVICE_OPTIONS, strategyProvider],
44
+ };
45
+ }
46
+ static sanitizeMSModuleOptions(options) {
47
+ options = { ...defaultOptions, ...options };
48
+ return options;
49
+ }
50
+ static createStrategyProvider(options) {
51
+ if (options.strategyProvider) {
52
+ return {
53
+ provide: strategy_1.MicroServiceStrategyProvider,
54
+ useClass: options.strategyProvider,
55
+ };
56
+ }
57
+ else {
58
+ return {
59
+ provide: strategy_1.MicroServiceStrategyProvider,
60
+ useFactory: async (options) => {
61
+ return new strategy_1.MicroServiceJwtStrategyProvider(options.options);
62
+ },
63
+ inject: [constant_1.MICROSERVICE_OPTIONS],
64
+ };
65
+ }
66
+ }
67
+ static createAsyncOptionsProviders(options) {
68
+ if (options.useExisting || options.useFactory) {
69
+ return [this.createAsyncOptionsProvider(options)];
70
+ }
71
+ return [
72
+ this.createAsyncOptionsProvider(options),
73
+ {
74
+ provide: options.useClass,
75
+ useClass: options.useClass,
76
+ },
77
+ ];
78
+ }
79
+ static createAsyncOptionsProvider(options) {
80
+ if (options.useFactory) {
81
+ return {
82
+ provide: constant_1.MICROSERVICE_OPTIONS,
83
+ useFactory: async (...args) => {
84
+ return this.sanitizeMSModuleOptions((await options.useFactory(...args)));
85
+ },
86
+ inject: options.inject || [],
87
+ };
88
+ }
89
+ return {
90
+ provide: constant_1.MICROSERVICE_OPTIONS,
91
+ useFactory: async (optionsFactory) => this.sanitizeMSModuleOptions((await optionsFactory.createOptions())),
92
+ inject: [options.useClass || options.useExisting]
93
+ };
94
+ }
95
+ };
96
+ MicroServiceModule = MicroServiceModule_1 = __decorate([
97
+ (0, common_1.Module)({})
98
+ ], MicroServiceModule);
99
+ exports.MicroServiceModule = MicroServiceModule;
100
+ let DefaultMicroServiceModuleOptionsFactory = class DefaultMicroServiceModuleOptionsFactory {
101
+ constructor() {
102
+ this.extraOptions = {
103
+ bindIp: false,
104
+ checkBlacklisted: false,
105
+ allowDuplicateLogin: true,
106
+ ignoreExpiration: false,
107
+ passReqToCallback: true,
108
+ };
109
+ }
110
+ createOptions() {
111
+ return {
112
+ options: {
113
+ secret: process.env.MS_JWT_ACCESS_SECRET,
114
+ publicKey: process.env.MS_JWT_ACCESS_PUBLICKEY,
115
+ privateKey: process.env.MS_JWT_ACCESS_PRIVATEKEY,
116
+ passphrase: process.env.MS_JWT_ACCESS_PASSPHRASE,
117
+ signOption: {
118
+ expiresIn: process.env.MS_JWT_ACCESS_EXPIRE,
119
+ algorithm: process.env.MS_JWT_ACCESS_ALGORITHM,
120
+ },
121
+ ...this.extraOptions,
122
+ },
123
+ };
124
+ }
125
+ };
126
+ DefaultMicroServiceModuleOptionsFactory = __decorate([
127
+ (0, common_1.Injectable)(),
128
+ __metadata("design:paramtypes", [])
129
+ ], DefaultMicroServiceModuleOptionsFactory);
130
+ exports.DefaultMicroServiceModuleOptionsFactory = DefaultMicroServiceModuleOptionsFactory;
@@ -0,0 +1,3 @@
1
+ import { MicroServiceJwtStrategyProvider, MicroServiceStrategyProvider } from "./microservice-jwt-strategy-provider";
2
+ import { MicroServiceJwtStrategy } from "./microservice-jwt.strategy";
3
+ export { MicroServiceJwtStrategyProvider, MicroServiceJwtStrategy, MicroServiceStrategyProvider, };
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MicroServiceStrategyProvider = exports.MicroServiceJwtStrategy = exports.MicroServiceJwtStrategyProvider = void 0;
4
+ const microservice_jwt_strategy_provider_1 = require("./microservice-jwt-strategy-provider");
5
+ Object.defineProperty(exports, "MicroServiceJwtStrategyProvider", { enumerable: true, get: function () { return microservice_jwt_strategy_provider_1.MicroServiceJwtStrategyProvider; } });
6
+ Object.defineProperty(exports, "MicroServiceStrategyProvider", { enumerable: true, get: function () { return microservice_jwt_strategy_provider_1.MicroServiceStrategyProvider; } });
7
+ const microservice_jwt_strategy_1 = require("./microservice-jwt.strategy");
8
+ Object.defineProperty(exports, "MicroServiceJwtStrategy", { enumerable: true, get: function () { return microservice_jwt_strategy_1.MicroServiceJwtStrategy; } });
@@ -0,0 +1,13 @@
1
+ import { IPrincipal, JwtOptions, JwtStrategyProvider, Req } from "@nathapp/nestjs-auth";
2
+ import { Request } from "express";
3
+ import { ParamsDictionary } from "express-serve-static-core";
4
+ import { ParsedQs } from "qs";
5
+ export declare abstract class MicroServiceStrategyProvider extends JwtStrategyProvider {
6
+ abstract validate(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, payload: any): IPrincipal | Promise<IPrincipal>;
7
+ abstract validate<T>(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, payload: any): T | Promise<T>;
8
+ }
9
+ export declare class MicroServiceJwtStrategyProvider extends MicroServiceStrategyProvider {
10
+ private readonly logger;
11
+ constructor(options: JwtOptions);
12
+ validate<T>(req: Req, payload: any): Promise<T>;
13
+ }
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MicroServiceJwtStrategyProvider = exports.MicroServiceStrategyProvider = void 0;
4
+ const nestjs_auth_1 = require("@nathapp/nestjs-auth");
5
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
6
+ const common_1 = require("@nestjs/common");
7
+ const util_1 = require("util");
8
+ class MicroServiceStrategyProvider extends nestjs_auth_1.JwtStrategyProvider {
9
+ }
10
+ exports.MicroServiceStrategyProvider = MicroServiceStrategyProvider;
11
+ class MicroServiceJwtStrategyProvider extends MicroServiceStrategyProvider {
12
+ constructor(options) {
13
+ super(options);
14
+ this.logger = new common_1.Logger(MicroServiceJwtStrategyProvider.name);
15
+ }
16
+ async validate(req, payload) {
17
+ this.logger.verbose(`MS JwtStrategyProvider: method: ${req.method}`);
18
+ if (req.method == "GET") {
19
+ throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
20
+ }
21
+ const omitExpPayload = payload;
22
+ delete omitExpPayload.iat;
23
+ delete omitExpPayload.exp;
24
+ this.logger.verbose(`MS JwtStrategyProvider: body: ${JSON.stringify(req.body)}, payload: ${JSON.stringify(payload)}`);
25
+ if (!(0, util_1.isDeepStrictEqual)(req.body, omitExpPayload)) {
26
+ throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.FORBIDDEN);
27
+ }
28
+ return payload;
29
+ }
30
+ }
31
+ exports.MicroServiceJwtStrategyProvider = MicroServiceJwtStrategyProvider;
@@ -0,0 +1,9 @@
1
+ import { Strategy } from "passport-jwt";
2
+ import { MicroServiceStrategyProvider } from "./microservice-jwt-strategy-provider";
3
+ declare const MicroServiceJwtStrategy_base: new (...args: any[]) => Strategy;
4
+ export declare class MicroServiceJwtStrategy extends MicroServiceJwtStrategy_base {
5
+ private readonly strategyProvider;
6
+ constructor(strategyProvider: MicroServiceStrategyProvider);
7
+ validate(arg1: any, arg2: any): Promise<any>;
8
+ }
9
+ export {};
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MicroServiceJwtStrategy = void 0;
13
+ const passport_jwt_1 = require("passport-jwt");
14
+ const passport_1 = require("@nestjs/passport");
15
+ const common_1 = require("@nestjs/common");
16
+ const constant_1 = require("../constant");
17
+ const microservice_jwt_strategy_provider_1 = require("./microservice-jwt-strategy-provider");
18
+ let MicroServiceJwtStrategy = class MicroServiceJwtStrategy extends (0, passport_1.PassportStrategy)(passport_jwt_1.Strategy, constant_1.MICROSERVICE_STRATEGY_NAME) {
19
+ constructor(strategyProvider) {
20
+ super({
21
+ jwtFromRequest: strategyProvider.jwtFromRequestFunction,
22
+ ignoreExpiration: strategyProvider.ignoreExpiration,
23
+ secretOrKey: strategyProvider.secretOrPublicKey,
24
+ passReqToCallback: strategyProvider.passReqToCallback,
25
+ });
26
+ this.strategyProvider = strategyProvider;
27
+ }
28
+ async validate(arg1, arg2) {
29
+ const req = this.strategyProvider.passReqToCallback ? arg1 : {};
30
+ const payload = this.strategyProvider.passReqToCallback ? arg2 : arg1;
31
+ return this.strategyProvider.validate(req, payload);
32
+ }
33
+ };
34
+ MicroServiceJwtStrategy = __decorate([
35
+ (0, common_1.Injectable)(),
36
+ __metadata("design:paramtypes", [microservice_jwt_strategy_provider_1.MicroServiceStrategyProvider])
37
+ ], MicroServiceJwtStrategy);
38
+ exports.MicroServiceJwtStrategy = MicroServiceJwtStrategy;
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./dist";
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ exports.__esModule = true;
6
+ __export(require("./dist"));
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@nathapp/nestjs-microservices",
3
+ "version": "1.0.0-rc.10",
4
+ "description": "nestjs-microservices",
5
+ "scripts": {
6
+ "build": "rimraf dist && tsc -p tsconfig.json",
7
+ "precommit": "lint-staged",
8
+ "test": "jest --config ./test/jest-test.json",
9
+ "test:cov": "jest --config ./test/jest-test.json --coverage",
10
+ "test:watch": "jest --config ./test/jest-test.json --watch",
11
+ "lint": "eslint -c .eslintrc.js"
12
+ },
13
+ "author": "",
14
+ "license": "ISC",
15
+ "devDependencies": {
16
+ "@golevelup/ts-jest": "^0.3.7",
17
+ "@nestjs/platform-express": "^9.0.0",
18
+ "@nestjs/platform-fastify": "^9.0.0",
19
+ "@nestjs/testing": "^9.4.3",
20
+ "@types/express": "^4.17.17",
21
+ "@types/jest": "^29.5.2",
22
+ "@types/node": "^17.0.22",
23
+ "@types/passport-jwt": "^3.0.8",
24
+ "@types/supertest": "^2.0.12",
25
+ "@typescript-eslint/eslint-plugin": "^4",
26
+ "@typescript-eslint/parser": "^4",
27
+ "eslint": "*",
28
+ "eslint-config-prettier": "^6",
29
+ "eslint-plugin-prettier": "^3",
30
+ "jest": "^29.5.0",
31
+ "prettier": "^2",
32
+ "supertest": "^6.3.3",
33
+ "ts-jest": "^29.1.0",
34
+ "typescript": "^4"
35
+ },
36
+ "types": "./index.d.ts",
37
+ "main": "index.js",
38
+ "directories": {
39
+ "lib": "lib"
40
+ },
41
+ "dependencies": {
42
+ "@nathapp/auth": "^1.0.1",
43
+ "@nathapp/nestjs-auth": "^1.0.0-rc.23",
44
+ "@nathapp/nestjs-common": "^1.0.1-rc.16",
45
+ "axios": "^1.4.0",
46
+ "passport-jwt": "^4.0.1"
47
+ },
48
+ "peerDependencies": {
49
+ "@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0",
50
+ "@nestjs/config": "^1.0.0 || ^2.0.0 || ^3.0.0",
51
+ "@nestjs/core": "^8.0.0 || ^9.0.0 || ^10.0.0",
52
+ "@nestjs/passport": "^8.0.0 || ^9.0.0 || ^10.0.0",
53
+ "class-transformer": "*",
54
+ "class-validator": "*",
55
+ "rxjs": "*"
56
+ }
57
+ }