@viardex/viardex-libs 1.0.11 → 1.0.13

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 (176) hide show
  1. package/README.md +12 -235
  2. package/dist/cache/index.cjs +229 -0
  3. package/dist/cache/index.cjs.map +1 -0
  4. package/dist/cache/{cache.service.d.ts → index.d.cts} +14 -4
  5. package/dist/cache/index.d.ts +40 -3
  6. package/dist/cache/index.js +191 -17
  7. package/dist/cache/index.js.map +1 -0
  8. package/dist/common/index.cjs +979 -0
  9. package/dist/common/index.cjs.map +1 -0
  10. package/dist/common/index.d.cts +214 -0
  11. package/dist/common/index.d.ts +214 -10
  12. package/dist/common/index.js +874 -26
  13. package/dist/common/index.js.map +1 -0
  14. package/dist/index.cjs +1661 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.cts +10 -0
  17. package/dist/index.d.ts +10 -9
  18. package/dist/index.js +1527 -25
  19. package/dist/index.js.map +1 -0
  20. package/dist/logger/index.cjs +209 -0
  21. package/dist/logger/index.cjs.map +1 -0
  22. package/dist/logger/index.d.cts +15 -0
  23. package/dist/logger/index.d.ts +14 -2
  24. package/dist/logger/index.js +181 -19
  25. package/dist/logger/index.js.map +1 -0
  26. package/dist/nats/index.cjs +271 -0
  27. package/dist/nats/index.cjs.map +1 -0
  28. package/dist/nats/{constants/nats.constants.d.ts → index.d.cts} +61 -18
  29. package/dist/nats/index.d.ts +200 -5
  30. package/dist/nats/index.js +225 -20
  31. package/dist/nats/index.js.map +1 -0
  32. package/dist/rpc/index.cjs +93 -0
  33. package/dist/rpc/index.cjs.map +1 -0
  34. package/dist/rpc/index.d.cts +22 -0
  35. package/dist/rpc/index.d.ts +7 -3
  36. package/dist/rpc/index.js +69 -63
  37. package/dist/rpc/index.js.map +1 -0
  38. package/package.json +31 -60
  39. package/dist/argon/argon.module.d.ts +0 -2
  40. package/dist/argon/argon.module.js +0 -21
  41. package/dist/argon/argon.service.d.ts +0 -6
  42. package/dist/argon/argon.service.js +0 -74
  43. package/dist/argon/index.d.ts +0 -2
  44. package/dist/argon/index.js +0 -18
  45. package/dist/auth/auth.constants.d.ts +0 -4
  46. package/dist/auth/auth.constants.js +0 -7
  47. package/dist/auth/auth.interfaces.d.ts +0 -19
  48. package/dist/auth/auth.interfaces.js +0 -2
  49. package/dist/auth/auth.module.d.ts +0 -2
  50. package/dist/auth/auth.module.js +0 -31
  51. package/dist/auth/auth.service.d.ts +0 -13
  52. package/dist/auth/auth.service.js +0 -104
  53. package/dist/auth/decorators/auth-token-types.decorator.d.ts +0 -2
  54. package/dist/auth/decorators/auth-token-types.decorator.js +0 -7
  55. package/dist/auth/decorators/current-auth.decorator.d.ts +0 -1
  56. package/dist/auth/decorators/current-auth.decorator.js +0 -10
  57. package/dist/auth/decorators/index.d.ts +0 -5
  58. package/dist/auth/decorators/index.js +0 -21
  59. package/dist/auth/decorators/permissions.decorator.d.ts +0 -1
  60. package/dist/auth/decorators/permissions.decorator.js +0 -7
  61. package/dist/auth/decorators/public.decorator.d.ts +0 -1
  62. package/dist/auth/decorators/public.decorator.js +0 -7
  63. package/dist/auth/decorators/roles.decorator.d.ts +0 -1
  64. package/dist/auth/decorators/roles.decorator.js +0 -7
  65. package/dist/auth/guards/auth.guard.d.ts +0 -10
  66. package/dist/auth/guards/auth.guard.js +0 -65
  67. package/dist/auth/guards/index.d.ts +0 -3
  68. package/dist/auth/guards/index.js +0 -19
  69. package/dist/auth/guards/permissions.guard.d.ts +0 -7
  70. package/dist/auth/guards/permissions.guard.js +0 -52
  71. package/dist/auth/guards/roles.guard.d.ts +0 -7
  72. package/dist/auth/guards/roles.guard.js +0 -53
  73. package/dist/auth/index.d.ts +0 -6
  74. package/dist/auth/index.js +0 -22
  75. package/dist/cache/cache.constants.d.ts +0 -1
  76. package/dist/cache/cache.constants.js +0 -4
  77. package/dist/cache/cache.interface.d.ts +0 -2
  78. package/dist/cache/cache.interface.js +0 -2
  79. package/dist/cache/cache.module.d.ts +0 -5
  80. package/dist/cache/cache.module.js +0 -31
  81. package/dist/cache/cache.service.js +0 -125
  82. package/dist/common/cards/card.utils.d.ts +0 -9
  83. package/dist/common/cards/card.utils.js +0 -48
  84. package/dist/common/cards/index.d.ts +0 -1
  85. package/dist/common/cards/index.js +0 -17
  86. package/dist/common/config/index.d.ts +0 -1
  87. package/dist/common/config/index.js +0 -17
  88. package/dist/common/config/nats.config.d.ts +0 -8
  89. package/dist/common/config/nats.config.js +0 -33
  90. package/dist/common/constants/index.d.ts +0 -2
  91. package/dist/common/constants/index.js +0 -18
  92. package/dist/common/constants/otp.constants.d.ts +0 -15
  93. package/dist/common/constants/otp.constants.js +0 -18
  94. package/dist/common/constants/queues.constants.d.ts +0 -9
  95. package/dist/common/constants/queues.constants.js +0 -12
  96. package/dist/common/crypto/crypto.utils.d.ts +0 -7
  97. package/dist/common/crypto/crypto.utils.js +0 -42
  98. package/dist/common/crypto/index.d.ts +0 -1
  99. package/dist/common/crypto/index.js +0 -17
  100. package/dist/common/dto/index.d.ts +0 -1
  101. package/dist/common/dto/index.js +0 -17
  102. package/dist/common/dto/pagination-query.dto.d.ts +0 -7
  103. package/dist/common/dto/pagination-query.dto.js +0 -51
  104. package/dist/common/enums/index.d.ts +0 -1
  105. package/dist/common/enums/index.js +0 -17
  106. package/dist/common/enums/otp.enum.d.ts +0 -16
  107. package/dist/common/enums/otp.enum.js +0 -20
  108. package/dist/common/interfaces/index.d.ts +0 -1
  109. package/dist/common/interfaces/index.js +0 -17
  110. package/dist/common/interfaces/response.interface.d.ts +0 -27
  111. package/dist/common/interfaces/response.interface.js +0 -2
  112. package/dist/common/pipes/file-validation.pipe.d.ts +0 -22
  113. package/dist/common/pipes/file-validation.pipe.js +0 -78
  114. package/dist/common/pipes/index.d.ts +0 -2
  115. package/dist/common/pipes/index.js +0 -18
  116. package/dist/common/pipes/pagination-query-cleaner.pipe.d.ts +0 -4
  117. package/dist/common/pipes/pagination-query-cleaner.pipe.js +0 -24
  118. package/dist/common/response/http-exception.filter.d.ts +0 -6
  119. package/dist/common/response/http-exception.filter.js +0 -61
  120. package/dist/common/response/http-only-exception.filter.d.ts +0 -5
  121. package/dist/common/response/http-only-exception.filter.js +0 -24
  122. package/dist/common/response/index.d.ts +0 -4
  123. package/dist/common/response/index.js +0 -20
  124. package/dist/common/response/response.interceptor.d.ts +0 -6
  125. package/dist/common/response/response.interceptor.js +0 -57
  126. package/dist/common/response/response.utils.d.ts +0 -6
  127. package/dist/common/response/response.utils.js +0 -34
  128. package/dist/common/utils/country.utils.d.ts +0 -1
  129. package/dist/common/utils/country.utils.js +0 -38
  130. package/dist/common/utils/date.utils.d.ts +0 -6
  131. package/dist/common/utils/date.utils.js +0 -48
  132. package/dist/common/utils/decimal.utils.d.ts +0 -3
  133. package/dist/common/utils/decimal.utils.js +0 -22
  134. package/dist/common/utils/format.utils.d.ts +0 -13
  135. package/dist/common/utils/format.utils.js +0 -127
  136. package/dist/common/utils/index.d.ts +0 -8
  137. package/dist/common/utils/index.js +0 -24
  138. package/dist/common/utils/random.utils.d.ts +0 -10
  139. package/dist/common/utils/random.utils.js +0 -27
  140. package/dist/common/utils/reference.utils.d.ts +0 -1
  141. package/dist/common/utils/reference.utils.js +0 -17
  142. package/dist/common/utils/string.utils.d.ts +0 -10
  143. package/dist/common/utils/string.utils.js +0 -34
  144. package/dist/common/utils/validation.utils.d.ts +0 -8
  145. package/dist/common/utils/validation.utils.js +0 -44
  146. package/dist/health/health.controller.d.ts +0 -19
  147. package/dist/health/health.controller.js +0 -103
  148. package/dist/health/health.module.d.ts +0 -2
  149. package/dist/health/health.module.js +0 -21
  150. package/dist/health/index.d.ts +0 -2
  151. package/dist/health/index.js +0 -18
  152. package/dist/logger/logger.module.d.ts +0 -2
  153. package/dist/logger/logger.module.js +0 -72
  154. package/dist/logger/logging.interceptor.d.ts +0 -8
  155. package/dist/logger/logging.interceptor.js +0 -66
  156. package/dist/nats/constants/nats.constants.js +0 -101
  157. package/dist/nats/decorators/nats-event-pattern.decorator.d.ts +0 -2
  158. package/dist/nats/decorators/nats-event-pattern.decorator.js +0 -11
  159. package/dist/nats/dto/nats-message.dto.d.ts +0 -5
  160. package/dist/nats/dto/nats-message.dto.js +0 -33
  161. package/dist/nats/interceptors/nats-logging.interceptor.d.ts +0 -6
  162. package/dist/nats/interceptors/nats-logging.interceptor.js +0 -33
  163. package/dist/nats/interfaces/nats-options.interface.d.ts +0 -23
  164. package/dist/nats/interfaces/nats-options.interface.js +0 -2
  165. package/dist/storage/index.d.ts +0 -5
  166. package/dist/storage/index.js +0 -21
  167. package/dist/storage/r2.service.d.ts +0 -20
  168. package/dist/storage/r2.service.js +0 -213
  169. package/dist/storage/s3.service.d.ts +0 -20
  170. package/dist/storage/s3.service.js +0 -209
  171. package/dist/storage/storage.interface.d.ts +0 -29
  172. package/dist/storage/storage.interface.js +0 -2
  173. package/dist/storage/storage.module.d.ts +0 -2
  174. package/dist/storage/storage.module.js +0 -24
  175. package/dist/storage/storage.service.d.ts +0 -22
  176. package/dist/storage/storage.service.js +0 -63
package/README.md CHANGED
@@ -1,249 +1,26 @@
1
1
  # Viardex Libs
2
2
 
3
- Shared NestJS infrastructure for Viardex services.
3
+ Shared TypeScript infrastructure library (`@viardex/viardex-libs`) for Viardex services.
4
4
 
5
- ## Argon
5
+ ## Modules
6
6
 
7
- `@viardex/viardex-libs` provides a shared Argon2id hashing module for passwords, passcodes, and transaction PINs.
7
+ - **`nats`**: JetStream client provider, connection factory, and message subject constants.
8
+ - **`cache`**: Redis connection abstractions and distributed caching utilities.
9
+ - **`common`**: Shared DTOs, custom decorators, validation schemas, and utility functions.
10
+ - **`rpc`**: Microservice RPC contracts and client patterns.
11
+ - **`logger`**: Structured JSON logging module wrapping `pino` with request correlation.
8
12
 
9
- ```ts
10
- import { ArgonModule, ArgonService } from '@viardex/viardex-libs';
11
-
12
- @Module({
13
- imports: [ArgonModule],
14
- })
15
- export class AppModule {}
16
- ```
13
+ ## Usage
17
14
 
18
- Example:
19
-
20
- ```ts
21
- constructor(private readonly argonService: ArgonService) {}
22
-
23
- const hash = await this.argonService.hash(password);
24
- const isValid = await this.argonService.verify(hash, password);
25
- const shouldRotate = await this.argonService.needsRehash(hash);
15
+ ```bash
16
+ npm install @viardex/viardex-libs
26
17
  ```
27
18
 
28
- `ArgonService.verify()` safely returns `false` for malformed hashes instead of leaking low-level argon exceptions into auth flows.
29
-
30
- ## Auth
31
-
32
- `@viardex/viardex-libs` provides the shared JWT verifier module.
33
-
34
19
  ```ts
35
- import { AuthModule } from '@viardex/viardex-libs';
20
+ import { NatsModule, NotificationSubjects } from '@viardex/viardex-libs';
36
21
 
37
22
  @Module({
38
- imports: [AuthModule],
23
+ imports: [NatsModule],
39
24
  })
40
25
  export class AppModule {}
41
26
  ```
42
-
43
- ### Decorators
44
-
45
- Use the shared barrel:
46
-
47
- ```ts
48
- import {
49
- AuthModule,
50
- CurrentAuth,
51
- Permissions,
52
- Public,
53
- Roles,
54
- } from '@viardex/viardex-libs';
55
- ```
56
-
57
- - `@Public()` marks a route as bypassing the global JWT guard.
58
- - `@Roles(...roles)` declares allowed staff roles for a route.
59
- - `@Permissions(...permissions)` declares required permissions for a route.
60
- - `@CurrentAuth()` returns the verified JWT principal from the request.
61
-
62
- ### Guards
63
-
64
- Guard classes live under `src/auth/guards` and are exported through the shared barrel:
65
-
66
- ```ts
67
- import { PermissionsGuard, RolesGuard } from '@viardex/viardex-libs';
68
- ```
69
-
70
- Example:
71
-
72
- ```ts
73
- @UseGuards(RolesGuard, PermissionsGuard)
74
- @Roles('admin', 'support')
75
- @Permissions('tickets.read', 'tickets.resolve')
76
- @Get('tickets')
77
- listTickets() {}
78
- ```
79
-
80
- ### JWT Config
81
-
82
- Services should expose:
83
-
84
- ```env
85
- JWT_ALGORITHM=RS256
86
- JWT_ISSUER=viardex-user-service
87
- JWT_AUDIENCE=viardex-api
88
- JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
89
- ```
90
-
91
- The shared auth module verifies JWTs globally. Role and permission guards are opt-in at the route or controller level.
92
-
93
- ## Logger
94
-
95
- `LoggerModule` is global and wraps `nestjs-pino`.
96
-
97
- - development uses `pino-pretty`
98
- - non-HTTP contexts are ignored by `LoggingInterceptor`
99
- - request logging keeps request id, method, URL, status code, and duration
100
-
101
- ## Health
102
-
103
- `HealthModule` exposes:
104
-
105
- - `GET /health` for lightweight liveness
106
- - `GET /health/ready` for readiness checks
107
-
108
- Readiness currently checks storage, memory, and NATS connectivity.
109
-
110
- ## Cache
111
-
112
- `CacheModule.register()` exposes a Redis-backed `CacheService`.
113
-
114
- Preferred APIs:
115
-
116
- - `set()` / `get()`
117
- - `setJson()` / `getJson()`
118
- - `setIfNotExists()` for idempotency / locks
119
- - `scan()` instead of `keys()` for production-safe pattern reads
120
- - `ping()` for lightweight health checks
121
-
122
- ## Common
123
-
124
- `@viardex/viardex-libs` also exposes shared DTOs, pipes, response helpers, and safe formatting utilities through the root barrel.
125
-
126
- ### Response Shape
127
-
128
- Use the shared response helpers to keep HTTP payloads consistent across Nest services.
129
-
130
- ```ts
131
- import { AppResponse } from '@viardex/viardex-libs';
132
-
133
- return AppResponse.success('User fetched successfully', user);
134
- ```
135
-
136
- For paginated endpoints:
137
-
138
- ```ts
139
- return AppResponse.paginated('Users fetched successfully', items, {
140
- page,
141
- limit,
142
- totalItems,
143
- totalPages,
144
- });
145
- ```
146
-
147
- Shared response exports include:
148
-
149
- - `ApiResponse`
150
- - `PaginationMeta`
151
- - `ResponseMeta`
152
- - `ErrorDetail`
153
- - `AppResponse`
154
- - `ResponseInterceptor`
155
- - `HttpExceptionFilter`
156
-
157
- ### DTOs And Pipes
158
-
159
- Shared request helpers include:
160
-
161
- - `PaginationQueryDto`
162
- - `PaginationQueryCleanerPipe`
163
- - `FileValidationPipe`
164
-
165
- ### Cards
166
-
167
- Shared card-safe helpers are available for masking and display use cases:
168
-
169
- - `maskPan`
170
- - `extractLast4`
171
- - `extractBin`
172
- - `formatCardExpiry`
173
- - `normalizeCardExpiry`
174
- - `formatCardLabel`
175
-
176
- These are for safe formatting and display only. Sensitive authentication data like CVV must never be stored or handled through shared helpers.
177
-
178
- ### Crypto
179
-
180
- Shared crypto helpers are intentionally limited to generic amount and formatting concerns:
181
-
182
- - `toAtomicUnits`
183
- - `fromAtomicUnits`
184
- - `formatCryptoAmount`
185
- - `normalizeTxHash`
186
- - `isHexTxHash`
187
- - `isPositiveAmount`
188
-
189
- They are useful for asset formatting and validation, but custody, compliance, signing, and chain-specific business logic should stay inside the owning service.
190
-
191
- ## Nest And Go Mapping
192
-
193
- The Go shared package in `viardex-go` follows the same auth concepts, but uses middleware and request context instead of Nest metadata and guards.
194
-
195
- | Nest (`viardex-libs`) | Go (`viardex-go`) |
196
- | --- | --- |
197
- | `AuthModule` | `auth` package setup in service bootstrap |
198
- | `AuthService` | `auth.NewService(...)` / `auth.Service` |
199
- | `AuthPrincipal` | `auth.Principal` |
200
- | `AuthTokenType` | `auth.TokenType` |
201
- | `AuthGuard` | `middlewares.Auth(...)` |
202
- | `RolesGuard` | `middlewares.RequireRoles(...)` |
203
- | `PermissionsGuard` | `middlewares.RequirePermissions(...)` |
204
- | `AuthTokenTypes(...)` | `middlewares.RequireTokenTypes(...)` |
205
- | `Public()` | keep route/group outside auth middleware |
206
- | `Roles(...)` | wrap route/group with `middlewares.RequireRoles(...)` |
207
- | `Permissions(...)` | wrap route/group with `middlewares.RequirePermissions(...)` |
208
- | `CurrentAuth()` | `auth.PrincipalFromContext(r.Context())` |
209
-
210
- ### Example Comparison
211
-
212
- Nest:
213
-
214
- ```ts
215
- @UseGuards(PermissionsGuard)
216
- @Permissions('ledger.read')
217
- @Get('/ledger')
218
- ```
219
-
220
- Go:
221
-
222
- ```go
223
- r.With(middlewares.RequirePermissions("ledger.read")).Get("/ledger", handler)
224
- ```
225
-
226
- Nest:
227
-
228
- ```ts
229
- @Public()
230
- @Get('/health')
231
- ```
232
-
233
- Go:
234
-
235
- ```go
236
- r.Get("/health", handler)
237
- ```
238
-
239
- Nest:
240
-
241
- ```ts
242
- const principal = request.user;
243
- ```
244
-
245
- Go:
246
-
247
- ```go
248
- principal, ok := auth.PrincipalFromContext(r.Context())
249
- ```
@@ -0,0 +1,229 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/cache/index.ts
31
+ var cache_exports = {};
32
+ __export(cache_exports, {
33
+ CACHE_MODULE_OPTIONS: () => CACHE_MODULE_OPTIONS,
34
+ CacheModule: () => CacheModule,
35
+ CacheService: () => CacheService
36
+ });
37
+ module.exports = __toCommonJS(cache_exports);
38
+
39
+ // src/cache/cache.constants.ts
40
+ var CACHE_MODULE_OPTIONS = /* @__PURE__ */ Symbol("CACHE_MODULE_OPTIONS");
41
+
42
+ // src/cache/cache.module.ts
43
+ var import_common2 = require("@nestjs/common");
44
+ var import_config = require("@nestjs/config");
45
+
46
+ // src/cache/cache.service.ts
47
+ var import_common = require("@nestjs/common");
48
+ var import_ioredis = __toESM(require("ioredis"), 1);
49
+ function _ts_decorate(decorators, target, key, desc) {
50
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
51
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
52
+ r = Reflect.decorate(decorators, target, key, desc);
53
+ } else {
54
+ for (var i = decorators.length - 1; i >= 0; i--) {
55
+ if (d = decorators[i]) {
56
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
57
+ }
58
+ }
59
+ }
60
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
61
+ }
62
+ __name(_ts_decorate, "_ts_decorate");
63
+ function _ts_metadata(metadataKey, metadataValue) {
64
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
65
+ return Reflect.metadata(metadataKey, metadataValue);
66
+ }
67
+ }
68
+ __name(_ts_metadata, "_ts_metadata");
69
+ function _ts_param(paramIndex, decorator) {
70
+ return function(target, key) {
71
+ decorator(target, key, paramIndex);
72
+ };
73
+ }
74
+ __name(_ts_param, "_ts_param");
75
+ var CacheService = class {
76
+ static {
77
+ __name(this, "CacheService");
78
+ }
79
+ options;
80
+ redisClient;
81
+ constructor(options) {
82
+ this.options = options;
83
+ }
84
+ async onModuleInit() {
85
+ const options = this.options || {};
86
+ this.redisClient = new import_ioredis.default({
87
+ ...options,
88
+ host: options.host || process.env.REDIS_HOST || "localhost",
89
+ port: options.port || +(process.env?.REDIS_PORT || 6379),
90
+ username: options.username || process.env?.REDIS_USERNAME,
91
+ password: options.password || process.env?.REDIS_PASSWORD,
92
+ keyPrefix: options.keyPrefix || "viardex:"
93
+ });
94
+ }
95
+ async onModuleDestroy() {
96
+ await this.redisClient.quit();
97
+ }
98
+ getClient() {
99
+ return this.redisClient;
100
+ }
101
+ async ping() {
102
+ return this.redisClient.ping();
103
+ }
104
+ async set(key, value, ttlSeconds) {
105
+ if (ttlSeconds) {
106
+ await this.redisClient.setex(key, ttlSeconds, value);
107
+ } else {
108
+ await this.redisClient.set(key, value);
109
+ }
110
+ }
111
+ async setIfNotExists(key, value, ttlSeconds) {
112
+ const result = ttlSeconds ? await this.redisClient.set(key, value, "EX", ttlSeconds, "NX") : await this.redisClient.set(key, value, "NX");
113
+ return result === "OK";
114
+ }
115
+ async get(key) {
116
+ return this.redisClient.get(key);
117
+ }
118
+ async setJson(key, value, ttlSeconds) {
119
+ await this.set(key, JSON.stringify(value), ttlSeconds);
120
+ }
121
+ async getJson(key) {
122
+ const value = await this.get(key);
123
+ return value ? JSON.parse(value) : null;
124
+ }
125
+ async del(key) {
126
+ await this.redisClient.del(key);
127
+ }
128
+ async exists(key) {
129
+ const result = await this.redisClient.exists(key);
130
+ return result === 1;
131
+ }
132
+ async ttl(key) {
133
+ return this.redisClient.ttl(key);
134
+ }
135
+ async keys(pattern) {
136
+ return this.redisClient.keys(pattern);
137
+ }
138
+ async scan(pattern, count = 100) {
139
+ const keys = [];
140
+ let cursor = "0";
141
+ do {
142
+ const [nextCursor, batch] = await this.redisClient.scan(cursor, "MATCH", pattern, "COUNT", count);
143
+ cursor = nextCursor;
144
+ keys.push(...batch);
145
+ } while (cursor !== "0");
146
+ return keys;
147
+ }
148
+ async flushAll() {
149
+ await this.redisClient.flushall();
150
+ }
151
+ async incr(key) {
152
+ return this.redisClient.incr(key);
153
+ }
154
+ async decr(key) {
155
+ return this.redisClient.decr(key);
156
+ }
157
+ async hset(key, field, value) {
158
+ await this.redisClient.hset(key, field, value);
159
+ }
160
+ async hget(key, field) {
161
+ return this.redisClient.hget(key, field);
162
+ }
163
+ async hgetall(key) {
164
+ return this.redisClient.hgetall(key);
165
+ }
166
+ async hdel(key, field) {
167
+ await this.redisClient.hdel(key, field);
168
+ }
169
+ async expire(key, ttlSeconds) {
170
+ await this.redisClient.expire(key, ttlSeconds);
171
+ }
172
+ };
173
+ CacheService = _ts_decorate([
174
+ (0, import_common.Injectable)(),
175
+ _ts_param(0, (0, import_common.Inject)(CACHE_MODULE_OPTIONS)),
176
+ _ts_metadata("design:type", Function),
177
+ _ts_metadata("design:paramtypes", [
178
+ typeof CacheOptions === "undefined" ? Object : CacheOptions
179
+ ])
180
+ ], CacheService);
181
+
182
+ // src/cache/cache.module.ts
183
+ function _ts_decorate2(decorators, target, key, desc) {
184
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
185
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
186
+ r = Reflect.decorate(decorators, target, key, desc);
187
+ } else {
188
+ for (var i = decorators.length - 1; i >= 0; i--) {
189
+ if (d = decorators[i]) {
190
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
191
+ }
192
+ }
193
+ }
194
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
195
+ }
196
+ __name(_ts_decorate2, "_ts_decorate");
197
+ var CacheModule = class _CacheModule {
198
+ static {
199
+ __name(this, "CacheModule");
200
+ }
201
+ static register(options = {}) {
202
+ return {
203
+ module: _CacheModule,
204
+ imports: [
205
+ import_config.ConfigModule
206
+ ],
207
+ providers: [
208
+ CacheService,
209
+ {
210
+ provide: CACHE_MODULE_OPTIONS,
211
+ useValue: options
212
+ }
213
+ ],
214
+ exports: [
215
+ CacheService
216
+ ]
217
+ };
218
+ }
219
+ };
220
+ CacheModule = _ts_decorate2([
221
+ (0, import_common2.Module)({})
222
+ ], CacheModule);
223
+ // Annotate the CommonJS export names for ESM import in node:
224
+ 0 && (module.exports = {
225
+ CACHE_MODULE_OPTIONS,
226
+ CacheModule,
227
+ CacheService
228
+ });
229
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cache/index.ts","../../src/cache/cache.constants.ts","../../src/cache/cache.module.ts","../../src/cache/cache.service.ts"],"sourcesContent":["export * from './cache.constants';\nexport * from './cache.module';\nexport * from './cache.service';\n","export const CACHE_MODULE_OPTIONS = Symbol('CACHE_MODULE_OPTIONS');\n","import { DynamicModule, Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { CacheService } from './cache.service';\nimport { CacheOptions } from './cache.interface';\nimport { CACHE_MODULE_OPTIONS } from './cache.constants';\n\n@Module({})\nexport class CacheModule {\n static register(options: CacheOptions = {}): DynamicModule {\n return {\n module: CacheModule,\n imports: [ConfigModule],\n providers: [\n CacheService,\n { provide: CACHE_MODULE_OPTIONS, useValue: options },\n ],\n exports: [CacheService],\n };\n }\n}\n","import {\n Inject,\n Injectable,\n OnModuleDestroy,\n OnModuleInit,\n} from '@nestjs/common';\nimport Redis from 'ioredis';\nimport type { CacheOptions } from './cache.interface';\nimport { CACHE_MODULE_OPTIONS } from './cache.constants';\n\n@Injectable()\nexport class CacheService implements OnModuleInit, OnModuleDestroy {\n private redisClient!: Redis;\n\n constructor(\n @Inject(CACHE_MODULE_OPTIONS) private readonly options: CacheOptions\n ) {}\n\n async onModuleInit() {\n const options = this.options || {};\n\n this.redisClient = new Redis({\n ...options,\n host: options.host || process.env.REDIS_HOST || 'localhost',\n port: options.port || +(process.env?.REDIS_PORT || 6379),\n username: options.username || process.env?.REDIS_USERNAME,\n password: options.password || process.env?.REDIS_PASSWORD,\n keyPrefix: options.keyPrefix || 'viardex:',\n });\n }\n\n async onModuleDestroy() {\n await this.redisClient.quit();\n }\n\n getClient(): Redis {\n return this.redisClient;\n }\n\n async ping(): Promise<string> {\n return this.redisClient.ping();\n }\n\n async set(key: string, value: string, ttlSeconds?: number): Promise<void> {\n if (ttlSeconds) {\n await this.redisClient.setex(key, ttlSeconds, value);\n } else {\n await this.redisClient.set(key, value);\n }\n }\n\n async setIfNotExists(\n key: string,\n value: string,\n ttlSeconds?: number\n ): Promise<boolean> {\n const result = ttlSeconds\n ? await this.redisClient.set(key, value, 'EX', ttlSeconds, 'NX')\n : await this.redisClient.set(key, value, 'NX');\n\n return result === 'OK';\n }\n\n async get(key: string): Promise<string | null> {\n return this.redisClient.get(key);\n }\n\n async setJson<T>(key: string, value: T, ttlSeconds?: number): Promise<void> {\n await this.set(key, JSON.stringify(value), ttlSeconds);\n }\n\n async getJson<T>(key: string): Promise<T | null> {\n const value = await this.get(key);\n return value ? (JSON.parse(value) as T) : null;\n }\n\n async del(key: string): Promise<void> {\n await this.redisClient.del(key);\n }\n\n async exists(key: string): Promise<boolean> {\n const result = await this.redisClient.exists(key);\n return result === 1;\n }\n\n async ttl(key: string): Promise<number> {\n return this.redisClient.ttl(key);\n }\n\n async keys(pattern: string): Promise<string[]> {\n return this.redisClient.keys(pattern);\n }\n\n async scan(pattern: string, count = 100): Promise<string[]> {\n const keys: string[] = [];\n let cursor = '0';\n\n do {\n const [nextCursor, batch] = await this.redisClient.scan(\n cursor,\n 'MATCH',\n pattern,\n 'COUNT',\n count\n );\n cursor = nextCursor;\n keys.push(...batch);\n } while (cursor !== '0');\n\n return keys;\n }\n\n async flushAll(): Promise<void> {\n await this.redisClient.flushall();\n }\n\n async incr(key: string): Promise<number> {\n return this.redisClient.incr(key);\n }\n\n async decr(key: string): Promise<number> {\n return this.redisClient.decr(key);\n }\n\n async hset(key: string, field: string, value: string): Promise<void> {\n await this.redisClient.hset(key, field, value);\n }\n\n async hget(key: string, field: string): Promise<string | null> {\n return this.redisClient.hget(key, field);\n }\n\n async hgetall(key: string): Promise<Record<string, string>> {\n return this.redisClient.hgetall(key);\n }\n\n async hdel(key: string, field: string): Promise<void> {\n await this.redisClient.hdel(key, field);\n }\n\n async expire(key: string, ttlSeconds: number): Promise<void> {\n await this.redisClient.expire(key, ttlSeconds);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA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AM4B,KAAK7B,KAAa4B,OAAuC;AAC7D,WAAO,KAAKhD,YAAYiD,KAAK7B,KAAK4B,KAAAA;EACpC;EAEA,MAAME,QAAQ9B,KAA8C;AAC1D,WAAO,KAAKpB,YAAYkD,QAAQ9B,GAAAA;EAClC;EAEA,MAAM+B,KAAK/B,KAAa4B,OAA8B;AACpD,UAAM,KAAKhD,YAAYmD,KAAK/B,KAAK4B,KAAAA;EACnC;EAEA,MAAMI,OAAOhC,KAAaE,YAAmC;AAC3D,UAAM,KAAKtB,YAAYoD,OAAOhC,KAAKE,UAAAA;EACrC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;ADxIO,IAAM+B,cAAN,MAAMA,aAAAA;SAAAA;;;EACX,OAAOC,SAASC,UAAwB,CAAC,GAAkB;AACzD,WAAO;MACLC,QAAQH;MACRI,SAAS;QAACC;;MACVC,WAAW;QACTC;QACA;UAAEC,SAASC;UAAsBC,UAAUR;QAAQ;;MAErDS,SAAS;QAACJ;;IACZ;EACF;AACF;;;;","names":["CACHE_MODULE_OPTIONS","Symbol","import_common","CacheService","redisClient","options","onModuleInit","Redis","host","process","env","REDIS_HOST","port","REDIS_PORT","username","REDIS_USERNAME","password","REDIS_PASSWORD","keyPrefix","onModuleDestroy","quit","getClient","ping","set","key","value","ttlSeconds","setex","setIfNotExists","result","get","setJson","JSON","stringify","getJson","parse","del","exists","ttl","keys","pattern","scan","count","cursor","nextCursor","batch","push","flushAll","flushall","incr","decr","hset","field","hget","hgetall","hdel","expire","CacheModule","register","options","module","imports","ConfigModule","providers","CacheService","provide","CACHE_MODULE_OPTIONS","useValue","exports"]}
@@ -1,7 +1,15 @@
1
- import { OnModuleDestroy, OnModuleInit } from '@nestjs/common';
2
- import Redis from 'ioredis';
3
- import type { CacheOptions } from './cache.interface';
4
- export declare class CacheService implements OnModuleInit, OnModuleDestroy {
1
+ import { DynamicModule, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
2
+ import { RedisOptions } from 'ioredis';
3
+
4
+ declare const CACHE_MODULE_OPTIONS: unique symbol;
5
+
6
+ type CacheOptions = RedisOptions;
7
+
8
+ declare class CacheModule {
9
+ static register(options?: CacheOptions): DynamicModule;
10
+ }
11
+
12
+ declare class CacheService implements OnModuleInit, OnModuleDestroy {
5
13
  private readonly options;
6
14
  private redisClient;
7
15
  constructor(options: CacheOptions);
@@ -28,3 +36,5 @@ export declare class CacheService implements OnModuleInit, OnModuleDestroy {
28
36
  hdel(key: string, field: string): Promise<void>;
29
37
  expire(key: string, ttlSeconds: number): Promise<void>;
30
38
  }
39
+
40
+ export { CACHE_MODULE_OPTIONS, CacheModule, CacheService };
@@ -1,3 +1,40 @@
1
- export * from './cache.constants';
2
- export * from './cache.module';
3
- export * from './cache.service';
1
+ import { DynamicModule, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
2
+ import { RedisOptions } from 'ioredis';
3
+
4
+ declare const CACHE_MODULE_OPTIONS: unique symbol;
5
+
6
+ type CacheOptions = RedisOptions;
7
+
8
+ declare class CacheModule {
9
+ static register(options?: CacheOptions): DynamicModule;
10
+ }
11
+
12
+ declare class CacheService implements OnModuleInit, OnModuleDestroy {
13
+ private readonly options;
14
+ private redisClient;
15
+ constructor(options: CacheOptions);
16
+ onModuleInit(): Promise<void>;
17
+ onModuleDestroy(): Promise<void>;
18
+ getClient(): Redis;
19
+ ping(): Promise<string>;
20
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
21
+ setIfNotExists(key: string, value: string, ttlSeconds?: number): Promise<boolean>;
22
+ get(key: string): Promise<string | null>;
23
+ setJson<T>(key: string, value: T, ttlSeconds?: number): Promise<void>;
24
+ getJson<T>(key: string): Promise<T | null>;
25
+ del(key: string): Promise<void>;
26
+ exists(key: string): Promise<boolean>;
27
+ ttl(key: string): Promise<number>;
28
+ keys(pattern: string): Promise<string[]>;
29
+ scan(pattern: string, count?: number): Promise<string[]>;
30
+ flushAll(): Promise<void>;
31
+ incr(key: string): Promise<number>;
32
+ decr(key: string): Promise<number>;
33
+ hset(key: string, field: string, value: string): Promise<void>;
34
+ hget(key: string, field: string): Promise<string | null>;
35
+ hgetall(key: string): Promise<Record<string, string>>;
36
+ hdel(key: string, field: string): Promise<void>;
37
+ expire(key: string, ttlSeconds: number): Promise<void>;
38
+ }
39
+
40
+ export { CACHE_MODULE_OPTIONS, CacheModule, CacheService };