@triproject/nestjs-core 1.0.5

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 (91) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +140 -0
  3. package/dist/bootstrap.d.ts +2 -0
  4. package/dist/bootstrap.js +43 -0
  5. package/dist/config.d.ts +46 -0
  6. package/dist/config.js +50 -0
  7. package/dist/controllers/controller.d.ts +8 -0
  8. package/dist/controllers/controller.js +56 -0
  9. package/dist/drivers/cache/cache.d.ts +18 -0
  10. package/dist/drivers/cache/cache.driver.d.ts +2 -0
  11. package/dist/drivers/cache/cache.driver.js +22 -0
  12. package/dist/drivers/cache/cache.js +92 -0
  13. package/dist/drivers/cache/index.d.ts +3 -0
  14. package/dist/drivers/cache/index.js +19 -0
  15. package/dist/drivers/cache/redis.d.ts +10 -0
  16. package/dist/drivers/cache/redis.js +52 -0
  17. package/dist/drivers/db/db.helper.d.ts +55 -0
  18. package/dist/drivers/db/db.helper.js +217 -0
  19. package/dist/drivers/db/db.module.d.ts +2 -0
  20. package/dist/drivers/db/db.module.js +44 -0
  21. package/dist/drivers/db/db.service.d.ts +10 -0
  22. package/dist/drivers/db/db.service.js +49 -0
  23. package/dist/drivers/db/index.d.ts +5 -0
  24. package/dist/drivers/db/index.js +21 -0
  25. package/dist/drivers/db/migration.d.ts +42 -0
  26. package/dist/drivers/db/migration.js +81 -0
  27. package/dist/drivers/db/repository.d.ts +41 -0
  28. package/dist/drivers/db/repository.js +255 -0
  29. package/dist/drivers/encryptions/encryption.d.ts +8 -0
  30. package/dist/drivers/encryptions/encryption.js +50 -0
  31. package/dist/drivers/encryptions/encryption.module.d.ts +2 -0
  32. package/dist/drivers/encryptions/encryption.module.js +24 -0
  33. package/dist/drivers/encryptions/index.d.ts +3 -0
  34. package/dist/drivers/encryptions/index.js +19 -0
  35. package/dist/drivers/encryptions/jwt.d.ts +6 -0
  36. package/dist/drivers/encryptions/jwt.js +46 -0
  37. package/dist/drivers/encryptions/password-hash.d.ts +11 -0
  38. package/dist/drivers/encryptions/password-hash.js +38 -0
  39. package/dist/drivers/encryptions/snap.signature.d.ts +32 -0
  40. package/dist/drivers/encryptions/snap.signature.js +110 -0
  41. package/dist/drivers/logger/app.logger.d.ts +23 -0
  42. package/dist/drivers/logger/app.logger.js +183 -0
  43. package/dist/drivers/logger/index.d.ts +2 -0
  44. package/dist/drivers/logger/index.js +18 -0
  45. package/dist/drivers/logger/slack.logger.d.ts +4 -0
  46. package/dist/drivers/logger/slack.logger.js +24 -0
  47. package/dist/drivers/mail/index.d.ts +6 -0
  48. package/dist/drivers/mail/index.js +22 -0
  49. package/dist/drivers/mail/mail-template.d.ts +8 -0
  50. package/dist/drivers/mail/mail-template.js +74 -0
  51. package/dist/drivers/mail/mail.config.d.ts +18 -0
  52. package/dist/drivers/mail/mail.config.js +4 -0
  53. package/dist/drivers/mail/mail.d.ts +23 -0
  54. package/dist/drivers/mail/mail.js +98 -0
  55. package/dist/drivers/mail/mail.module.d.ts +2 -0
  56. package/dist/drivers/mail/mail.module.js +26 -0
  57. package/dist/drivers/mail/mail.queue.d.ts +9 -0
  58. package/dist/drivers/mail/mail.queue.js +37 -0
  59. package/dist/drivers/mail/mailer.d.ts +13 -0
  60. package/dist/drivers/mail/mailer.js +62 -0
  61. package/dist/drivers/notifications/index.d.ts +5 -0
  62. package/dist/drivers/notifications/index.js +21 -0
  63. package/dist/drivers/notifications/notification.config.d.ts +8 -0
  64. package/dist/drivers/notifications/notification.config.js +4 -0
  65. package/dist/drivers/notifications/notification.module.d.ts +2 -0
  66. package/dist/drivers/notifications/notification.module.js +25 -0
  67. package/dist/drivers/notifications/notification.queue.d.ts +9 -0
  68. package/dist/drivers/notifications/notification.queue.js +37 -0
  69. package/dist/drivers/notifications/push-notification.d.ts +10 -0
  70. package/dist/drivers/notifications/push-notification.js +75 -0
  71. package/dist/drivers/notifications/slack.d.ts +15 -0
  72. package/dist/drivers/notifications/slack.js +95 -0
  73. package/dist/drivers/queues/app.queue.d.ts +11 -0
  74. package/dist/drivers/queues/app.queue.js +66 -0
  75. package/dist/drivers/queues/index.d.ts +2 -0
  76. package/dist/drivers/queues/index.js +18 -0
  77. package/dist/drivers/queues/queue.module.d.ts +2 -0
  78. package/dist/drivers/queues/queue.module.js +41 -0
  79. package/dist/helpers/exception.helper.d.ts +35 -0
  80. package/dist/helpers/exception.helper.js +71 -0
  81. package/dist/helpers/http.helper.d.ts +23 -0
  82. package/dist/helpers/http.helper.js +134 -0
  83. package/dist/helpers/swagger.helper.d.ts +20 -0
  84. package/dist/helpers/swagger.helper.js +287 -0
  85. package/dist/helpers/totp.helper.d.ts +16 -0
  86. package/dist/helpers/totp.helper.js +30 -0
  87. package/dist/index.d.ts +8 -0
  88. package/dist/index.js +24 -0
  89. package/dist/middlewares/log.middleware.d.ts +9 -0
  90. package/dist/middlewares/log.middleware.js +59 -0
  91. package/package.json +145 -0
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2024 Triyanto
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,140 @@
1
+ # @triproject/nestjs
2
+
3
+ Opinionated NestJS building blocks for caching, configuration, queues, logging, mail, notifications, encryption, and database access.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @triproject/nestjs
9
+ ```
10
+
11
+ ## Modular Imports
12
+
13
+ This package uses subpath exports to avoid loading unnecessary dependencies. Import only what you need:
14
+
15
+ ### Bootstrap (Core)
16
+
17
+ ```typescript
18
+ import { bootstrap } from '@triproject/nestjs/bootstrap';
19
+ import { APP_PORT, APP_KEY } from '@triproject/nestjs/config';
20
+ ```
21
+
22
+ Required peer dependencies:
23
+
24
+ - `@nestjs/common`
25
+ - `@nestjs/core`
26
+ - `express`
27
+ - `helmet`
28
+ - `cookie-parser`
29
+ - `class-validator`
30
+
31
+ ### Cache (Redis)
32
+
33
+ ```typescript
34
+ import { AppCache, Redis, CacheModule } from '@triproject/nestjs/cache';
35
+ ```
36
+
37
+ Required peer dependencies:
38
+
39
+ - `redis` (^4.0.0 || ^5.0.0)
40
+
41
+ ### Database (Sequelize)
42
+
43
+ ```typescript
44
+ import { DatabaseModule, Repository } from '@triproject/nestjs/db';
45
+ ```
46
+
47
+ Required peer dependencies:
48
+
49
+ - `sequelize` (^6.0.0)
50
+ - `sequelize-typescript` (^2.0.0)
51
+ - `@nestjs/sequelize` (^11.0.0)
52
+
53
+ ### Encryption & JWT
54
+
55
+ ```typescript
56
+ import { PasswordHash, Jwt, EncryptionModule } from '@triproject/nestjs/encryption';
57
+ ```
58
+
59
+ Required peer dependencies:
60
+
61
+ - `jsonwebtoken` (^9.0.0)
62
+
63
+ ### Logger
64
+
65
+ ```typescript
66
+ import { AppLogger, SlackLogger } from '@triproject/nestjs/logger';
67
+ ```
68
+
69
+ No additional dependencies required (uses `axios` from core).
70
+
71
+ ### Mail
72
+
73
+ ```typescript
74
+ import { MailModule, Mailer } from '@triproject/nestjs/mail';
75
+ ```
76
+
77
+ Required peer dependencies:
78
+
79
+ - `nodemailer` (^6.0.0 || ^7.0.0)
80
+ - `@nestjs/bull` (^11.0.0)
81
+ - `bull` (^4.0.0)
82
+
83
+ ### Notifications
84
+
85
+ ```typescript
86
+ import { NotificationModule, PushNotification } from '@triproject/nestjs/notifications';
87
+ ```
88
+
89
+ Required peer dependencies:
90
+
91
+ - `@nestjs/bull` (^11.0.0)
92
+ - `bull` (^4.0.0)
93
+
94
+ ### Queues (BullMQ)
95
+
96
+ ```typescript
97
+ import { QueueModule, AppQueue } from '@triproject/nestjs/queues';
98
+ ```
99
+
100
+ Required peer dependencies:
101
+
102
+ - `@nestjs/bullmq` (^11.0.0)
103
+ - `bullmq` (^5.0.0)
104
+
105
+ ### Helpers
106
+
107
+ ```typescript
108
+ import { HttpExceptionFilter, SwaggerHelper, Totp } from '@triproject/nestjs/helpers';
109
+ ```
110
+
111
+ Required peer dependencies for TOTP:
112
+
113
+ - `speakeasy` (^2.0.0)
114
+ - `qrcode` (^1.5.0)
115
+
116
+ ## Usage Example
117
+
118
+ ```typescript
119
+ // app.module.ts
120
+ import { Module } from '@nestjs/common';
121
+ import { CacheModule } from '@triproject/nestjs/cache';
122
+ import { DatabaseModule } from '@triproject/nestjs/db';
123
+ import { EncryptionModule } from '@triproject/nestjs/encryption';
124
+
125
+ @Module({
126
+ imports: [CacheModule, DatabaseModule, EncryptionModule],
127
+ })
128
+ export class AppModule {}
129
+
130
+ // main.ts
131
+ import { bootstrap } from '@triproject/nestjs/bootstrap';
132
+ import { setupSwagger } from './swagger';
133
+ import { AppModule } from './app.module';
134
+
135
+ bootstrap(AppModule, setupSwagger);
136
+ ```
137
+
138
+ ## License
139
+
140
+ ISC
@@ -0,0 +1,2 @@
1
+ import { INestApplication } from '@nestjs/common';
2
+ export declare function bootstrap(module: any, swaggerSetup?: (app: INestApplication) => void): Promise<void>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.bootstrap = bootstrap;
7
+ const common_1 = require("@nestjs/common");
8
+ const core_1 = require("@nestjs/core");
9
+ const cookie_parser_1 = __importDefault(require("cookie-parser"));
10
+ const helmet_1 = __importDefault(require("helmet"));
11
+ const config_1 = require("./config");
12
+ const app_logger_1 = require("./drivers/logger/app.logger");
13
+ const http_helper_1 = require("./helpers/http.helper");
14
+ async function bootstrap(module, swaggerSetup) {
15
+ const logger = new app_logger_1.AppLogger(`Bootstrap App`);
16
+ const app = await core_1.NestFactory.create(module, { rawBody: true, logger });
17
+ app.use((0, cookie_parser_1.default)());
18
+ app.useGlobalPipes(new common_1.ValidationPipe({
19
+ skipMissingProperties: true,
20
+ whitelist: true,
21
+ transform: true,
22
+ transformOptions: {
23
+ enableImplicitConversion: true,
24
+ },
25
+ }));
26
+ app.use((0, helmet_1.default)());
27
+ app.useGlobalFilters(new http_helper_1.HttpExceptionFilter());
28
+ app.useGlobalInterceptors(new http_helper_1.TransformResponseInterceptor());
29
+ app.enableCors({
30
+ origin: config_1.ALLOWED_ORIGINS,
31
+ credentials: true,
32
+ });
33
+ if (swaggerSetup)
34
+ swaggerSetup(app);
35
+ await app
36
+ .listen(config_1.APP_PORT)
37
+ .then(() => {
38
+ logger.log(`Server started on port ${config_1.APP_PORT}`);
39
+ if (swaggerSetup)
40
+ logger.log(`Swagger docs available at http://localhost:${config_1.APP_PORT}/docs`);
41
+ })
42
+ .catch((error) => logger.error('Failed to start server', error));
43
+ }
@@ -0,0 +1,46 @@
1
+ import { Dialect } from 'sequelize';
2
+ export declare const NODE_ENV: string;
3
+ export declare const APP_NAME: string;
4
+ export declare const APP_PORT: number;
5
+ export declare const APP_KEY: string;
6
+ export declare const SESSION_KEY: string;
7
+ export declare const SESSION_EXPIRATION: number;
8
+ export declare const ALLOWED_ORIGINS: string[];
9
+ export declare const PASSWORD_HASH_SECRET: string;
10
+ export declare const ENCRYPTION_KEY: string | undefined;
11
+ export declare const JWT_PUBLIC_KEY: string;
12
+ export declare const JWT_PRIVATE_KEY: string;
13
+ export declare const DB_DIALECT: Dialect;
14
+ export declare const DB_HOST: string;
15
+ export declare const DB_PORT: number;
16
+ export declare const DB_USER: string;
17
+ export declare const DB_PASSWORD: string;
18
+ export declare const DB_NAME: string;
19
+ export declare const DB_REPLICA_HOST: string;
20
+ export declare const DB_REPLICA_PORT: number;
21
+ export declare const DB_SSL: boolean;
22
+ export declare const DB_MAX_POOL_SIZE: number;
23
+ export declare const DB_POOL_MIN: number;
24
+ export declare const DB_POOL_ACQUIRE: number;
25
+ export declare const DB_POOL_IDLE: number;
26
+ export declare const DB_ENTITIES_PATH = "./dist/**/**/*.entity.*";
27
+ export declare const REDIS_HOST: string;
28
+ export declare const REDIS_PORT: number;
29
+ export declare const REDIS_DB: number;
30
+ export declare const REDIS_PASSWORD: string;
31
+ export declare const REDIS_TLS: boolean;
32
+ export declare const MAIL_MAILER: 'smtp' | 'ses';
33
+ export declare const MAIL_HOST: string;
34
+ export declare const MAIL_PORT: number;
35
+ export declare const MAIL_USERNAME: string;
36
+ export declare const MAIL_PASSWORD: string;
37
+ export declare const MAIL_ENCRYPTION: 'tls' | 'ssl' | 'false';
38
+ export declare const MAIL_FROM_NAME: string;
39
+ export declare const MAIL_FROM_EMAIL: string;
40
+ export declare const MAIL_TO_CC: string;
41
+ export declare const MAIL_EMAIL_SUPPORT: string;
42
+ export declare const SLACK_ERROR_WEBHOOK_URL: string;
43
+ export declare const LANDING_PAGE_URL: string;
44
+ export declare const APP_LOGO_URL: string;
45
+ export declare const ONESIGNAL_APP_ID: string;
46
+ export declare const ONESIGNAL_REST_API_KEY: string;
package/dist/config.js ADDED
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ONESIGNAL_REST_API_KEY = exports.ONESIGNAL_APP_ID = exports.APP_LOGO_URL = exports.LANDING_PAGE_URL = exports.SLACK_ERROR_WEBHOOK_URL = exports.MAIL_EMAIL_SUPPORT = exports.MAIL_TO_CC = exports.MAIL_FROM_EMAIL = exports.MAIL_FROM_NAME = exports.MAIL_ENCRYPTION = exports.MAIL_PASSWORD = exports.MAIL_USERNAME = exports.MAIL_PORT = exports.MAIL_HOST = exports.MAIL_MAILER = exports.REDIS_TLS = exports.REDIS_PASSWORD = exports.REDIS_DB = exports.REDIS_PORT = exports.REDIS_HOST = exports.DB_ENTITIES_PATH = exports.DB_POOL_IDLE = exports.DB_POOL_ACQUIRE = exports.DB_POOL_MIN = exports.DB_MAX_POOL_SIZE = exports.DB_SSL = exports.DB_REPLICA_PORT = exports.DB_REPLICA_HOST = exports.DB_NAME = exports.DB_PASSWORD = exports.DB_USER = exports.DB_PORT = exports.DB_HOST = exports.DB_DIALECT = exports.JWT_PRIVATE_KEY = exports.JWT_PUBLIC_KEY = exports.ENCRYPTION_KEY = exports.PASSWORD_HASH_SECRET = exports.ALLOWED_ORIGINS = exports.SESSION_EXPIRATION = exports.SESSION_KEY = exports.APP_KEY = exports.APP_PORT = exports.APP_NAME = exports.NODE_ENV = void 0;
4
+ const dotenv_1 = require("dotenv");
5
+ (0, dotenv_1.config)({ quiet: true });
6
+ exports.NODE_ENV = process.env.NODE_ENV ?? 'development';
7
+ exports.APP_NAME = process.env.APP_NAME ?? 'MyApp';
8
+ exports.APP_PORT = Number(process.env.APP_PORT) ?? 3000;
9
+ exports.APP_KEY = process.env.APP_KEY ?? '';
10
+ exports.SESSION_KEY = process.env.SESSION_KEY ?? 'APP_SESSION';
11
+ exports.SESSION_EXPIRATION = Number(process.env.SESSION_EXPIRATION) ?? 86400;
12
+ exports.ALLOWED_ORIGINS = (process.env.ALLOWED_ORIGINS ?? 'http://localhost:3000').split(',');
13
+ exports.PASSWORD_HASH_SECRET = process.env.PASSWORD_HASH_SECRET ?? 'default_secret';
14
+ exports.ENCRYPTION_KEY = process.env.ENCRYPTION_KEY;
15
+ exports.JWT_PUBLIC_KEY = process.env.JWT_PUBLIC_KEY ?? '';
16
+ exports.JWT_PRIVATE_KEY = process.env.JWT_PRIVATE_KEY ?? '';
17
+ exports.DB_DIALECT = 'postgres';
18
+ exports.DB_HOST = process.env.DB_HOST ?? 'localhost';
19
+ exports.DB_PORT = Number(process.env.DB_PORT) ?? 5432;
20
+ exports.DB_USER = process.env.DB_USER ?? 'postgres';
21
+ exports.DB_PASSWORD = process.env.DB_PASSWORD ?? 'password';
22
+ exports.DB_NAME = process.env.DB_NAME ?? 'postgres';
23
+ exports.DB_REPLICA_HOST = process.env.DB_REPLICA_HOST ?? 'localhost';
24
+ exports.DB_REPLICA_PORT = Number(process.env.DB_REPLICA_PORT) ?? 5432;
25
+ exports.DB_SSL = (process.env.DB_SSL ?? 'false')?.toLowerCase() === 'true';
26
+ exports.DB_MAX_POOL_SIZE = Number(process.env.DB_MAX_POOL_SIZE ?? 10);
27
+ exports.DB_POOL_MIN = Number(process.env.DB_POOL_MIN ?? 0);
28
+ exports.DB_POOL_ACQUIRE = Number(process.env.DB_POOL_ACQUIRE ?? 30000);
29
+ exports.DB_POOL_IDLE = Number(process.env.DB_POOL_IDLE ?? 10000);
30
+ exports.DB_ENTITIES_PATH = './dist/**/**/*.entity.*';
31
+ exports.REDIS_HOST = process.env.REDIS_HOST ?? 'localhost';
32
+ exports.REDIS_PORT = Number(process.env.REDIS_PORT) ?? 6379;
33
+ exports.REDIS_DB = Number(process.env.REDIS_DB) ?? 0;
34
+ exports.REDIS_PASSWORD = process.env.REDIS_PASSWORD ?? '';
35
+ exports.REDIS_TLS = (process.env.REDIS_TLS ?? 'false')?.toLowerCase() === 'true';
36
+ exports.MAIL_MAILER = process.env.MAIL_MAILER ?? 'smtp';
37
+ exports.MAIL_HOST = process.env.MAIL_HOST ?? '127.0.0.1';
38
+ exports.MAIL_PORT = +(process.env.MAIL_PORT ?? 1025);
39
+ exports.MAIL_USERNAME = process.env.MAIL_USERNAME ?? '';
40
+ exports.MAIL_PASSWORD = process.env.MAIL_PASSWORD ?? '';
41
+ exports.MAIL_ENCRYPTION = (process.env.MAIL_ENCRYPTION ?? 'false');
42
+ exports.MAIL_FROM_NAME = process.env.MAIL_FROM_NAME ?? 'Support Team';
43
+ exports.MAIL_FROM_EMAIL = process.env.MAIL_FROM_EMAIL ?? 'no-reply@app.com';
44
+ exports.MAIL_TO_CC = process.env.MAIL_TO_CC ?? '';
45
+ exports.MAIL_EMAIL_SUPPORT = process.env.MAIL_EMAIL_SUPPORT ?? 'support@app.com';
46
+ exports.SLACK_ERROR_WEBHOOK_URL = process.env.SLACK_ERROR_WEBHOOK_URL ?? '';
47
+ exports.LANDING_PAGE_URL = process.env.LANDING_PAGE_URL ?? 'http://localhost:8000';
48
+ exports.APP_LOGO_URL = process.env.APP_LOGO_URL ?? '';
49
+ exports.ONESIGNAL_APP_ID = process.env.ONESIGNAL_APP_ID ?? '';
50
+ exports.ONESIGNAL_REST_API_KEY = process.env.ONESIGNAL_REST_API_KEY ?? '';
@@ -0,0 +1,8 @@
1
+ export declare class AppController {
2
+ private req;
3
+ private appCache;
4
+ private _cacheKey;
5
+ cache<T>(callback: () => Promise<T>, ttl?: number): Promise<T>;
6
+ cacheWithTimestamp<T>(callback: () => Promise<T>, ttl?: number): Promise<import("../drivers/cache").CacheWithTimestamp<string | number | object>>;
7
+ clearCache(): Promise<void>;
8
+ }
@@ -0,0 +1,56 @@
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.AppController = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const core_1 = require("@nestjs/core");
15
+ const helpers_1 = require("@triproject/helpers");
16
+ const cache_1 = require("../drivers/cache");
17
+ const swagger_helper_1 = require("../helpers/swagger.helper");
18
+ let AppController = class AppController {
19
+ req;
20
+ appCache;
21
+ _cacheKey() {
22
+ const keys = [this.constructor.name, this.req.path, this.req.method];
23
+ if (this.req.query && Object.keys(this.req.query).length) {
24
+ keys.push((0, helpers_1.qs)(this.req.query));
25
+ }
26
+ if (this.req.body && Object.keys(this.req.body).length) {
27
+ keys.push((0, helpers_1.qs)(this.req.body));
28
+ }
29
+ return keys;
30
+ }
31
+ async cache(callback, ttl = 60) {
32
+ return await this.appCache.cache(this._cacheKey(), callback, ttl);
33
+ }
34
+ async cacheWithTimestamp(callback, ttl = 60) {
35
+ return await this.appCache.cacheWithTimeStamp(this._cacheKey(), callback, ttl);
36
+ }
37
+ async clearCache() {
38
+ await this.appCache.delAll([this.constructor.name]);
39
+ }
40
+ };
41
+ exports.AppController = AppController;
42
+ __decorate([
43
+ (0, common_1.Inject)(core_1.REQUEST),
44
+ __metadata("design:type", Object)
45
+ ], AppController.prototype, "req", void 0);
46
+ __decorate([
47
+ (0, common_1.Inject)(cache_1.AppCache),
48
+ __metadata("design:type", cache_1.AppCache)
49
+ ], AppController.prototype, "appCache", void 0);
50
+ exports.AppController = AppController = __decorate([
51
+ swagger_helper_1.SwaggerApiInternalServerErrorResponse,
52
+ swagger_helper_1.SwaggerApiBadSwaGatewayResponse,
53
+ swagger_helper_1.SwaggerApiConflictResponse,
54
+ swagger_helper_1.SwaggerApiForbiddenResponse,
55
+ swagger_helper_1.SwaggerApiUnauthorizedResponse
56
+ ], AppController);
@@ -0,0 +1,18 @@
1
+ import { Redis } from './redis';
2
+ export type CacheKey = string | number | boolean | (string | number | boolean)[];
3
+ export interface CacheWithTimestamp<T> {
4
+ data: T;
5
+ timestamp: string;
6
+ }
7
+ export declare class AppCache {
8
+ private connection;
9
+ private PREFIX;
10
+ constructor(redis: Redis);
11
+ private _parseKey;
12
+ set<T>(key: CacheKey, value: T, ttl?: number): Promise<void>;
13
+ get<T>(key: CacheKey): Promise<T | undefined>;
14
+ del(key: CacheKey): Promise<void>;
15
+ delAll(key: CacheKey): Promise<void>;
16
+ cache<T>(key: CacheKey, fn: () => Promise<any>, ttl?: number): Promise<T>;
17
+ cacheWithTimeStamp<T extends object | string | number>(key: CacheKey, value: () => Promise<T> | T, ttl?: number): Promise<CacheWithTimestamp<T>>;
18
+ }
@@ -0,0 +1,2 @@
1
+ export declare class CacheModule {
2
+ }
@@ -0,0 +1,22 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.CacheModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const cache_1 = require("./cache");
12
+ const redis_1 = require("./redis");
13
+ let CacheModule = class CacheModule {
14
+ };
15
+ exports.CacheModule = CacheModule;
16
+ exports.CacheModule = CacheModule = __decorate([
17
+ (0, common_1.Global)(),
18
+ (0, common_1.Module)({
19
+ providers: [redis_1.Redis, cache_1.AppCache],
20
+ exports: [cache_1.AppCache],
21
+ })
22
+ ], CacheModule);
@@ -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 __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.AppCache = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const helpers_1 = require("@triproject/helpers");
15
+ const config_1 = require("../../config");
16
+ const redis_1 = require("./redis");
17
+ let AppCache = class AppCache {
18
+ connection;
19
+ PREFIX = config_1.APP_KEY;
20
+ constructor(redis) {
21
+ this.connection = redis.getConnection();
22
+ }
23
+ _parseKey(key) {
24
+ if (!key)
25
+ throw new common_1.UnprocessableEntityException('Cache key cannot be null or undefined');
26
+ const keys = [this.PREFIX];
27
+ if (Array.isArray(key))
28
+ keys.push(...key);
29
+ else
30
+ keys.push(key?.toString());
31
+ return keys
32
+ .flat()
33
+ .flat()
34
+ .filter((d) => d)
35
+ .map((d) => d?.toString()?.toUpperCase())
36
+ .join(':');
37
+ }
38
+ async set(key, value, ttl = 60) {
39
+ await this.connection.set(this._parseKey(key), JSON.stringify({ data: value }), {
40
+ expiration: { type: 'EX', value: ttl * 1000 },
41
+ });
42
+ }
43
+ async get(key) {
44
+ try {
45
+ const data = await this.connection.get(this._parseKey(key));
46
+ if (!data)
47
+ return undefined;
48
+ const parsedData = JSON.parse(data?.toString());
49
+ return parsedData?.data;
50
+ }
51
+ catch (error) {
52
+ return;
53
+ }
54
+ }
55
+ async del(key) {
56
+ await this.connection.del(this._parseKey(key));
57
+ }
58
+ async delAll(key) {
59
+ const keys = await this.connection.hGetAll(`*${this.PREFIX}*${this._parseKey(key)}*`);
60
+ for (const k in keys)
61
+ await this.connection.del(k);
62
+ }
63
+ async cache(key, fn, ttl = 60) {
64
+ const data = await this.get(key);
65
+ if (data)
66
+ return data;
67
+ const result = await fn();
68
+ await this.set(key, result, ttl);
69
+ return result;
70
+ }
71
+ async cacheWithTimeStamp(key, value, ttl) {
72
+ try {
73
+ let data = await this.get(key);
74
+ if (data)
75
+ return data;
76
+ data = {
77
+ data: (typeof data === 'function' ? await value() : value),
78
+ timestamp: (0, helpers_1.dateUtil)().utc().toString(),
79
+ };
80
+ this.set(key, data, ttl);
81
+ return data;
82
+ }
83
+ catch (error) {
84
+ throw error;
85
+ }
86
+ }
87
+ };
88
+ exports.AppCache = AppCache;
89
+ exports.AppCache = AppCache = __decorate([
90
+ (0, common_1.Injectable)(),
91
+ __metadata("design:paramtypes", [redis_1.Redis])
92
+ ], AppCache);
@@ -0,0 +1,3 @@
1
+ export * from './cache';
2
+ export * from './cache.driver';
3
+ export * from './redis';
@@ -0,0 +1,19 @@
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("./cache"), exports);
18
+ __exportStar(require("./cache.driver"), exports);
19
+ __exportStar(require("./redis"), exports);
@@ -0,0 +1,10 @@
1
+ import { OnModuleInit } from '@nestjs/common';
2
+ import { RedisClientType } from 'redis';
3
+ export declare class Redis implements OnModuleInit {
4
+ private logger;
5
+ private connection;
6
+ constructor();
7
+ private _connect;
8
+ getConnection(): RedisClientType;
9
+ onModuleInit(): Promise<void>;
10
+ }
@@ -0,0 +1,52 @@
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 Redis_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.Redis = void 0;
14
+ const common_1 = require("@nestjs/common");
15
+ const redis_1 = require("redis");
16
+ const config_1 = require("../../config");
17
+ const app_logger_1 = require("../logger/app.logger");
18
+ let Redis = Redis_1 = class Redis {
19
+ logger = new app_logger_1.AppLogger(Redis_1.name);
20
+ connection;
21
+ constructor() {
22
+ this.connection = (0, redis_1.createClient)({
23
+ database: config_1.REDIS_DB,
24
+ password: config_1.REDIS_PASSWORD,
25
+ socket: {
26
+ host: config_1.REDIS_HOST,
27
+ port: config_1.REDIS_PORT,
28
+ tls: config_1.REDIS_TLS,
29
+ },
30
+ });
31
+ }
32
+ async _connect() {
33
+ await this.connection
34
+ .connect()
35
+ .then(() => this.logger.log('Established connection to Redis'))
36
+ .catch((err) => this.logger.error('Unable to connect to Redis', err));
37
+ this.connection.on('connect', () => this.logger.log('Established connection to Redis'));
38
+ this.connection.on('error', (err) => this.logger.error('Failed to connect to Redis', err));
39
+ this.connection.on('reconnecting', () => this.logger.log('Reconnecting to Redis'));
40
+ }
41
+ getConnection() {
42
+ return this.connection;
43
+ }
44
+ async onModuleInit() {
45
+ await this._connect();
46
+ }
47
+ };
48
+ exports.Redis = Redis;
49
+ exports.Redis = Redis = Redis_1 = __decorate([
50
+ (0, common_1.Injectable)(),
51
+ __metadata("design:paramtypes", [])
52
+ ], Redis);
@@ -0,0 +1,55 @@
1
+ import { MapFromList } from '@triproject/helpers';
2
+ import { Attributes, IncludeOptions, ModelAttributeColumnOptions, WhereOptions } from 'sequelize';
3
+ import { Model } from 'sequelize-typescript';
4
+ import { Fn } from 'sequelize/types/utils';
5
+ export type OrderDataType = 'ASC' | 'DESC';
6
+ export type KeyOfModel<M extends Model> = (keyof Attributes<M>)[][number];
7
+ export declare class PaginateResponse<T> {
8
+ data: T[];
9
+ timestamp: string;
10
+ meta: {
11
+ total: number;
12
+ totalPage: number;
13
+ perPage: number;
14
+ prevPage: null | number;
15
+ page: number;
16
+ nextPage: null | number;
17
+ };
18
+ }
19
+ export type NestedOrders = ([string, OrderDataType] | [string, string, OrderDataType] | [string, string, string, OrderDataType])[];
20
+ export declare class PaginateRequest<M extends Model> {
21
+ perPage?: number;
22
+ page?: number;
23
+ q?: string;
24
+ orderBy?: KeyOfModel<M>;
25
+ sort?: OrderDataType;
26
+ searchKey?: KeyOfModel<M> | KeyOfModel<M>[];
27
+ order?: NestedOrders;
28
+ include?: IncludeOptions[];
29
+ where?: WhereOptions<M>;
30
+ orWhere?: WhereOptions<M>[];
31
+ andWhere?: WhereOptions<M>[];
32
+ attributes?: (string | [Fn, string])[];
33
+ groupBy?: string | string[];
34
+ }
35
+ export declare function PrimaryUuidCol(): Function;
36
+ export declare function PrimaryCodeCol(): Function;
37
+ export declare function PrimaryNumberCol(): Function;
38
+ export declare function CreatedAtCol(): Function;
39
+ export declare function UpdatedAtCol(): Function;
40
+ export declare function ForeignUuidCol(params?: {
41
+ allowNull?: boolean;
42
+ }): Function;
43
+ export declare function NumberCol(precision?: number, scale?: number, options?: Partial<ModelAttributeColumnOptions>): Function;
44
+ export declare function BooleanCol(defaultValue?: boolean): Function;
45
+ export declare function NameCol(): Function;
46
+ export declare function EnumCol<T>(data: MapFromList<T>): Function;
47
+ export declare function SchedulerCol(): (_target: any, _propertyKey: string) => void;
48
+ export declare class Entity<M extends {}> extends Model<M, Partial<M>> {
49
+ id: string;
50
+ createdAt: Date;
51
+ updatedAt: Date;
52
+ }
53
+ export declare class RelationEntity<M extends {}> extends Model<M, Partial<M>> {
54
+ id: number;
55
+ }