@flusys/nestjs-shared 6.0.1 → 6.1.0

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 (81) hide show
  1. package/cjs/classes/api-controller.class.spec.js +684 -0
  2. package/cjs/classes/api-service.class.spec.js +809 -0
  3. package/cjs/classes/handle-custome-db.spec.js +82 -0
  4. package/cjs/classes/hybrid-cache.class.spec.js +168 -0
  5. package/cjs/classes/winston.logger.class.spec.js +330 -0
  6. package/cjs/constants/index.js +1 -1
  7. package/cjs/decorators/api-response.decorator.spec.js +126 -0
  8. package/cjs/decorators/current-user.decorator.spec.js +74 -0
  9. package/cjs/decorators/log-action.decorator.spec.js +353 -0
  10. package/cjs/decorators/public.decorator.spec.js +50 -0
  11. package/cjs/decorators/require-permission.decorator.spec.js +147 -0
  12. package/cjs/exceptions/base-app.exception.spec.js +157 -0
  13. package/cjs/exceptions/permission.exception.spec.js +82 -0
  14. package/cjs/filters/global-exception.filter.spec.js +440 -0
  15. package/cjs/guards/jwt-auth.guard.spec.js +75 -0
  16. package/cjs/guards/optional-jwt-auth.guard.spec.js +55 -0
  17. package/cjs/guards/permission.guard.js +11 -10
  18. package/cjs/guards/permission.guard.spec.js +358 -0
  19. package/cjs/interceptors/delete-empty-id-from-body.interceptor.spec.js +107 -0
  20. package/cjs/interceptors/idempotency.interceptor.spec.js +116 -0
  21. package/cjs/interceptors/response-meta.interceptor.spec.js +89 -0
  22. package/cjs/interceptors/set-user-field-on-body.interceptor.spec.js +128 -0
  23. package/cjs/interceptors/slug.interceptor.spec.js +110 -0
  24. package/cjs/interfaces/index.js +1 -0
  25. package/cjs/interfaces/permission-sync-adapter.interface.js +11 -0
  26. package/cjs/middlewares/logger.middleware.spec.js +462 -0
  27. package/cjs/modules/cache/cache.module.spec.js +48 -0
  28. package/cjs/modules/datasource/multi-tenant-datasource.service.spec.js +381 -0
  29. package/cjs/modules/utils/utils.service.spec.js +169 -0
  30. package/cjs/utils/date-time.util.spec.js +84 -0
  31. package/cjs/utils/html-sanitizer.util.spec.js +76 -0
  32. package/cjs/utils/index.js +1 -0
  33. package/cjs/utils/permission-cache-key.util.js +31 -0
  34. package/cjs/utils/permission-cache-key.util.spec.js +88 -0
  35. package/cjs/utils/query-helpers.util.spec.js +209 -0
  36. package/cjs/utils/request.util.spec.js +249 -0
  37. package/cjs/utils/string.util.spec.js +63 -0
  38. package/constants/index.d.ts +1 -1
  39. package/fesm/classes/api-controller.class.spec.js +680 -0
  40. package/fesm/classes/api-service.class.spec.js +805 -0
  41. package/fesm/classes/handle-custome-db.spec.js +78 -0
  42. package/fesm/classes/hybrid-cache.class.spec.js +164 -0
  43. package/fesm/classes/winston.logger.class.spec.js +327 -0
  44. package/fesm/constants/index.js +1 -1
  45. package/fesm/decorators/api-response.decorator.spec.js +122 -0
  46. package/fesm/decorators/current-user.decorator.spec.js +73 -0
  47. package/fesm/decorators/log-action.decorator.spec.js +349 -0
  48. package/fesm/decorators/public.decorator.spec.js +46 -0
  49. package/fesm/decorators/require-permission.decorator.spec.js +143 -0
  50. package/fesm/exceptions/base-app.exception.spec.js +153 -0
  51. package/fesm/exceptions/permission.exception.spec.js +78 -0
  52. package/fesm/filters/global-exception.filter.spec.js +436 -0
  53. package/fesm/guards/jwt-auth.guard.spec.js +71 -0
  54. package/fesm/guards/optional-jwt-auth.guard.spec.js +51 -0
  55. package/fesm/guards/permission.guard.js +12 -11
  56. package/fesm/guards/permission.guard.spec.js +354 -0
  57. package/fesm/interceptors/delete-empty-id-from-body.interceptor.spec.js +103 -0
  58. package/fesm/interceptors/idempotency.interceptor.spec.js +112 -0
  59. package/fesm/interceptors/response-meta.interceptor.spec.js +85 -0
  60. package/fesm/interceptors/set-user-field-on-body.interceptor.spec.js +124 -0
  61. package/fesm/interceptors/slug.interceptor.spec.js +106 -0
  62. package/fesm/interfaces/index.js +1 -0
  63. package/fesm/interfaces/permission-sync-adapter.interface.js +1 -0
  64. package/fesm/middlewares/logger.middleware.spec.js +459 -0
  65. package/fesm/modules/cache/cache.module.spec.js +44 -0
  66. package/fesm/modules/datasource/multi-tenant-datasource.service.spec.js +377 -0
  67. package/fesm/modules/utils/utils.service.spec.js +165 -0
  68. package/fesm/utils/date-time.util.spec.js +80 -0
  69. package/fesm/utils/html-sanitizer.util.spec.js +72 -0
  70. package/fesm/utils/index.js +1 -0
  71. package/fesm/utils/permission-cache-key.util.js +10 -0
  72. package/fesm/utils/permission-cache-key.util.spec.js +84 -0
  73. package/fesm/utils/query-helpers.util.spec.js +205 -0
  74. package/fesm/utils/request.util.spec.js +245 -0
  75. package/fesm/utils/string.util.spec.js +59 -0
  76. package/guards/permission.guard.d.ts +0 -1
  77. package/interfaces/index.d.ts +1 -0
  78. package/interfaces/permission-sync-adapter.interface.d.ts +7 -0
  79. package/package.json +2 -2
  80. package/utils/index.d.ts +1 -0
  81. package/utils/permission-cache-key.util.d.ts +9 -0
@@ -0,0 +1,381 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ const _common = require("@nestjs/common");
6
+ const _multitenantdatasourceservice = require("./multi-tenant-datasource.service");
7
+ const _constants = require("../../constants");
8
+ function _define_property(obj, key, value) {
9
+ if (key in obj) {
10
+ Object.defineProperty(obj, key, {
11
+ value: value,
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true
15
+ });
16
+ } else {
17
+ obj[key] = value;
18
+ }
19
+ return obj;
20
+ }
21
+ const mockInitialize = jest.fn();
22
+ const mockDestroy = jest.fn();
23
+ const mockGetRepository = jest.fn();
24
+ let FakeDataSource = class FakeDataSource {
25
+ constructor(options){
26
+ _define_property(this, "isInitialized", false);
27
+ _define_property(this, "options", void 0);
28
+ _define_property(this, "initialize", jest.fn(async ()=>{
29
+ this.isInitialized = true;
30
+ await mockInitialize(this.options);
31
+ return this;
32
+ }));
33
+ _define_property(this, "destroy", jest.fn(async ()=>{
34
+ this.isInitialized = false;
35
+ await mockDestroy();
36
+ }));
37
+ _define_property(this, "getRepository", (entity)=>mockGetRepository(entity));
38
+ this.options = options;
39
+ }
40
+ };
41
+ jest.mock('typeorm', ()=>({
42
+ ...jest.requireActual('typeorm'),
43
+ DataSource: FakeDataSource
44
+ }));
45
+ function resetStatics() {
46
+ const cls = _multitenantdatasourceservice.MultiTenantDataSourceService;
47
+ cls.tenantConnections = new Map();
48
+ cls.singleDataSource = null;
49
+ cls.tenantsRegistry = new Map();
50
+ cls.initialized = false;
51
+ cls.connectionLocks = new Map();
52
+ cls.singleConnectionLock = null;
53
+ }
54
+ describe('MultiTenantDataSourceService', ()=>{
55
+ const defaultDatabaseConfig = {
56
+ type: 'postgres',
57
+ host: 'localhost',
58
+ port: 5432,
59
+ username: 'root',
60
+ password: 'pw',
61
+ database: 'flusys_default'
62
+ };
63
+ beforeEach(()=>{
64
+ jest.clearAllMocks();
65
+ resetStatics();
66
+ });
67
+ function makeOptions(overrides = {}) {
68
+ return {
69
+ defaultDatabaseConfig,
70
+ bootstrapAppConfig: {
71
+ databaseMode: 'single'
72
+ },
73
+ ...overrides
74
+ };
75
+ }
76
+ function makeRequest(headers = {}) {
77
+ return {
78
+ headers
79
+ };
80
+ }
81
+ describe('database mode', ()=>{
82
+ it('should default to single mode when no options are provided', ()=>{
83
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService();
84
+ expect(service.getDatabaseMode()).toBe('single');
85
+ expect(service.isMultiTenant()).toBe(false);
86
+ });
87
+ it('should report multi-tenant mode from bootstrap config', ()=>{
88
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions({
89
+ bootstrapAppConfig: {
90
+ databaseMode: 'multi-tenant'
91
+ }
92
+ }));
93
+ expect(service.isMultiTenant()).toBe(true);
94
+ });
95
+ });
96
+ describe('tenant registration', ()=>{
97
+ it('should register tenants from options exactly once across instances', ()=>{
98
+ const tenants = [
99
+ {
100
+ id: 'tenant-a',
101
+ database: 'db_a'
102
+ },
103
+ {
104
+ id: 'tenant-b',
105
+ database: 'db_b'
106
+ }
107
+ ];
108
+ const options = makeOptions({
109
+ tenants
110
+ });
111
+ const service1 = new _multitenantdatasourceservice.MultiTenantDataSourceService(options);
112
+ const service2 = new _multitenantdatasourceservice.MultiTenantDataSourceService(options);
113
+ expect(service1.getTenant('tenant-a')?.database).toBe('db_a');
114
+ expect(service2.getTenant('tenant-b')?.database).toBe('db_b');
115
+ });
116
+ it('should return null for an unregistered tenant', ()=>{
117
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions());
118
+ expect(service.getTenant('unknown')).toBeNull();
119
+ });
120
+ it('should be a no-op when constructed without options', ()=>{
121
+ expect(()=>new _multitenantdatasourceservice.MultiTenantDataSourceService()).not.toThrow();
122
+ });
123
+ });
124
+ describe('getCurrentTenantId', ()=>{
125
+ it('should return null when there is no request (e.g. background job)', ()=>{
126
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions());
127
+ expect(service.getCurrentTenantId()).toBeNull();
128
+ });
129
+ it('should return null when the tenant header is missing', ()=>{
130
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions(), makeRequest());
131
+ expect(service.getCurrentTenantId()).toBeNull();
132
+ });
133
+ it('should return the tenant id from the header when valid', ()=>{
134
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions(), makeRequest({
135
+ 'x-tenant-id': 'tenant-a'
136
+ }));
137
+ expect(service.getCurrentTenantId()).toBe('tenant-a');
138
+ });
139
+ it('should reject tenant ids with invalid characters', ()=>{
140
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions(), makeRequest({
141
+ 'x-tenant-id': 'tenant a; DROP TABLE users;'
142
+ }));
143
+ expect(()=>service.getCurrentTenantId()).toThrow(_common.BadRequestException);
144
+ try {
145
+ service.getCurrentTenantId();
146
+ } catch (e) {
147
+ expect(e.getResponse().messageKey).toBe(_constants.SYSTEM_MESSAGES.INVALID_TENANT_ID);
148
+ }
149
+ });
150
+ it('should accept tenant ids with letters, numbers, underscores and dashes', ()=>{
151
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions(), makeRequest({
152
+ 'x-tenant-id': 'Tenant_123-ABC'
153
+ }));
154
+ expect(service.getCurrentTenantId()).toBe('Tenant_123-ABC');
155
+ });
156
+ });
157
+ describe('getCurrentTenant', ()=>{
158
+ it('should resolve the registered tenant config for the current request', ()=>{
159
+ const tenants = [
160
+ {
161
+ id: 'tenant-a',
162
+ database: 'db_a'
163
+ }
164
+ ];
165
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions({
166
+ tenants
167
+ }), makeRequest({
168
+ 'x-tenant-id': 'tenant-a'
169
+ }));
170
+ expect(service.getCurrentTenant()?.database).toBe('db_a');
171
+ });
172
+ it('should return null when there is no current tenant id', ()=>{
173
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions(), makeRequest());
174
+ expect(service.getCurrentTenant()).toBeNull();
175
+ });
176
+ });
177
+ describe('getSingleDataSource / getDataSource (single mode)', ()=>{
178
+ it('should create and initialize a datasource from the default config', async ()=>{
179
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions());
180
+ const ds = await service.getDataSource();
181
+ expect(ds.isInitialized).toBe(true);
182
+ expect(mockInitialize).toHaveBeenCalledWith(expect.objectContaining({
183
+ database: 'flusys_default'
184
+ }));
185
+ });
186
+ it('should reuse the cached datasource on subsequent calls', async ()=>{
187
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions());
188
+ const ds1 = await service.getDataSource();
189
+ const ds2 = await service.getDataSource();
190
+ expect(ds1).toBe(ds2);
191
+ expect(mockInitialize).toHaveBeenCalledTimes(1);
192
+ });
193
+ it('should dedupe concurrent creation attempts into a single connection', async ()=>{
194
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions());
195
+ const [ds1, ds2] = await Promise.all([
196
+ service.getDataSource(),
197
+ service.getDataSource()
198
+ ]);
199
+ expect(ds1).toBe(ds2);
200
+ expect(mockInitialize).toHaveBeenCalledTimes(1);
201
+ });
202
+ it('should throw InternalServerErrorException when no database config is available', async ()=>{
203
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions({
204
+ defaultDatabaseConfig: undefined
205
+ }));
206
+ await expect(service.getDataSource()).rejects.toThrow(_common.InternalServerErrorException);
207
+ });
208
+ it('should fall back to tenantDefaultDatabaseConfig when defaultDatabaseConfig is absent', async ()=>{
209
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions({
210
+ defaultDatabaseConfig: undefined,
211
+ tenantDefaultDatabaseConfig: defaultDatabaseConfig
212
+ }));
213
+ const ds = await service.getDataSource();
214
+ expect(ds.isInitialized).toBe(true);
215
+ });
216
+ it('getRepository should resolve the datasource then delegate to it', async ()=>{
217
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions());
218
+ let Product = class Product {
219
+ };
220
+ mockGetRepository.mockReturnValue('the-repo');
221
+ const repo = await service.getRepository(Product);
222
+ expect(mockGetRepository).toHaveBeenCalledWith(Product);
223
+ expect(repo).toBe('the-repo');
224
+ });
225
+ });
226
+ describe('getTenantDataSource / getDataSource (multi-tenant mode)', ()=>{
227
+ function multiTenantOptions(tenants) {
228
+ return makeOptions({
229
+ bootstrapAppConfig: {
230
+ databaseMode: 'multi-tenant'
231
+ },
232
+ tenants
233
+ });
234
+ }
235
+ it('should throw BadRequestException when no tenant header is present', async ()=>{
236
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(multiTenantOptions([
237
+ {
238
+ id: 'tenant-a',
239
+ database: 'db_a'
240
+ }
241
+ ]), makeRequest());
242
+ await expect(service.getDataSource()).rejects.toThrow(_common.BadRequestException);
243
+ });
244
+ it('should throw BadRequestException when the tenant is not registered', async ()=>{
245
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(multiTenantOptions([]), makeRequest({
246
+ 'x-tenant-id': 'ghost-tenant'
247
+ }));
248
+ await expect(service.getDataSource()).rejects.toThrow(_common.BadRequestException);
249
+ });
250
+ it('should create a tenant-specific connection merging tenant overrides onto the default config', async ()=>{
251
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(multiTenantOptions([
252
+ {
253
+ id: 'tenant-a',
254
+ database: 'db_a',
255
+ host: 'tenant-a-host'
256
+ }
257
+ ]), makeRequest({
258
+ 'x-tenant-id': 'tenant-a'
259
+ }));
260
+ const ds = await service.getDataSource();
261
+ expect(ds.isInitialized).toBe(true);
262
+ expect(mockInitialize).toHaveBeenCalledWith(expect.objectContaining({
263
+ database: 'db_a',
264
+ host: 'tenant-a-host',
265
+ username: defaultDatabaseConfig.username
266
+ }));
267
+ });
268
+ it('should cache the tenant connection and reuse it for subsequent requests to the same tenant', async ()=>{
269
+ const tenants = [
270
+ {
271
+ id: 'tenant-a',
272
+ database: 'db_a'
273
+ }
274
+ ];
275
+ const service1 = new _multitenantdatasourceservice.MultiTenantDataSourceService(multiTenantOptions(tenants), makeRequest({
276
+ 'x-tenant-id': 'tenant-a'
277
+ }));
278
+ const service2 = new _multitenantdatasourceservice.MultiTenantDataSourceService(multiTenantOptions(tenants), makeRequest({
279
+ 'x-tenant-id': 'tenant-a'
280
+ }));
281
+ const ds1 = await service1.getDataSource();
282
+ const ds2 = await service2.getDataSource();
283
+ expect(ds1).toBe(ds2);
284
+ expect(mockInitialize).toHaveBeenCalledTimes(1);
285
+ });
286
+ it('should maintain separate connections per tenant', async ()=>{
287
+ const tenants = [
288
+ {
289
+ id: 'tenant-a',
290
+ database: 'db_a'
291
+ },
292
+ {
293
+ id: 'tenant-b',
294
+ database: 'db_b'
295
+ }
296
+ ];
297
+ const serviceA = new _multitenantdatasourceservice.MultiTenantDataSourceService(multiTenantOptions(tenants), makeRequest({
298
+ 'x-tenant-id': 'tenant-a'
299
+ }));
300
+ const serviceB = new _multitenantdatasourceservice.MultiTenantDataSourceService(multiTenantOptions(tenants), makeRequest({
301
+ 'x-tenant-id': 'tenant-b'
302
+ }));
303
+ const dsA = await serviceA.getDataSource();
304
+ const dsB = await serviceB.getDataSource();
305
+ expect(dsA).not.toBe(dsB);
306
+ expect(mockInitialize).toHaveBeenCalledTimes(2);
307
+ });
308
+ it('should throw InternalServerErrorException when no default config exists to base tenant configs on', async ()=>{
309
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService({
310
+ ...multiTenantOptions([
311
+ {
312
+ id: 'tenant-a',
313
+ database: 'db_a'
314
+ }
315
+ ]),
316
+ defaultDatabaseConfig: undefined,
317
+ tenantDefaultDatabaseConfig: undefined
318
+ }, makeRequest({
319
+ 'x-tenant-id': 'tenant-a'
320
+ }));
321
+ await expect(service.getDataSource()).rejects.toThrow(_common.InternalServerErrorException);
322
+ });
323
+ });
324
+ describe('closeTenantConnection', ()=>{
325
+ it('should destroy and remove an initialized tenant connection', async ()=>{
326
+ const tenants = [
327
+ {
328
+ id: 'tenant-a',
329
+ database: 'db_a'
330
+ }
331
+ ];
332
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions({
333
+ bootstrapAppConfig: {
334
+ databaseMode: 'multi-tenant'
335
+ },
336
+ tenants
337
+ }), makeRequest({
338
+ 'x-tenant-id': 'tenant-a'
339
+ }));
340
+ await service.getDataSource();
341
+ await service.closeTenantConnection('tenant-a');
342
+ expect(mockDestroy).toHaveBeenCalledTimes(1);
343
+ expect(_multitenantdatasourceservice.MultiTenantDataSourceService.tenantConnections.has('tenant-a')).toBe(false);
344
+ });
345
+ it('should be a no-op for a tenant with no active connection', async ()=>{
346
+ const service = new _multitenantdatasourceservice.MultiTenantDataSourceService(makeOptions());
347
+ await expect(service.closeTenantConnection('never-connected')).resolves.toBeUndefined();
348
+ expect(mockDestroy).not.toHaveBeenCalled();
349
+ });
350
+ });
351
+ describe('onModuleDestroy', ()=>{
352
+ it('should close every tracked tenant connection', async ()=>{
353
+ const tenants = [
354
+ {
355
+ id: 'tenant-a',
356
+ database: 'db_a'
357
+ },
358
+ {
359
+ id: 'tenant-b',
360
+ database: 'db_b'
361
+ }
362
+ ];
363
+ const options = makeOptions({
364
+ bootstrapAppConfig: {
365
+ databaseMode: 'multi-tenant'
366
+ },
367
+ tenants
368
+ });
369
+ const serviceA = new _multitenantdatasourceservice.MultiTenantDataSourceService(options, makeRequest({
370
+ 'x-tenant-id': 'tenant-a'
371
+ }));
372
+ const serviceB = new _multitenantdatasourceservice.MultiTenantDataSourceService(options, makeRequest({
373
+ 'x-tenant-id': 'tenant-b'
374
+ }));
375
+ await serviceA.getDataSource();
376
+ await serviceB.getDataSource();
377
+ await serviceA.onModuleDestroy();
378
+ expect(mockDestroy).toHaveBeenCalledTimes(2);
379
+ });
380
+ });
381
+ });
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ const _utilsservice = require("./utils.service");
6
+ describe('UtilsService', ()=>{
7
+ let service;
8
+ let mockCache;
9
+ beforeEach(()=>{
10
+ service = new _utilsservice.UtilsService();
11
+ mockCache = {
12
+ get: jest.fn(),
13
+ set: jest.fn(),
14
+ del: jest.fn()
15
+ };
16
+ });
17
+ describe('getCacheKey', ()=>{
18
+ it('should build an "all" key from the entity name and params when no id is given', ()=>{
19
+ const key = service.getCacheKey('product', {
20
+ page: 1
21
+ });
22
+ expect(key).toBe('entity_product_all_{"page":1}');
23
+ });
24
+ it('should build a per-id key with a select suffix when params are given', ()=>{
25
+ const key = service.getCacheKey('product', {
26
+ fields: [
27
+ 'name'
28
+ ]
29
+ }, 'prod-1');
30
+ expect(key).toBe('entity_product_id_prod-1_select_{"fields":["name"]}');
31
+ });
32
+ it('should build a per-id key without a select suffix when params are falsy', ()=>{
33
+ const key = service.getCacheKey('product', null, 'prod-1');
34
+ expect(key).toBe('entity_product_id_prod-1');
35
+ });
36
+ it('should prefix the key with the tenant id when provided', ()=>{
37
+ const key = service.getCacheKey('product', {
38
+ page: 1
39
+ }, undefined, 'tenant-a');
40
+ expect(key).toBe('tenant_tenant-a_entity_product_all_{"page":1}');
41
+ });
42
+ it('should prefix a per-id key with the tenant id too', ()=>{
43
+ const key = service.getCacheKey('product', undefined, 'prod-1', 'tenant-a');
44
+ expect(key).toBe('tenant_tenant-a_entity_product_id_prod-1');
45
+ });
46
+ });
47
+ describe('trackCacheKey', ()=>{
48
+ it('should create a new tracking list when none exists yet', async ()=>{
49
+ mockCache.get.mockResolvedValue(undefined);
50
+ await service.trackCacheKey('cache-key-1', 'product', mockCache);
51
+ expect(mockCache.set).toHaveBeenCalledWith('entity_product_keys', [
52
+ 'cache-key-1'
53
+ ]);
54
+ });
55
+ it('should append to an existing tracking list without duplicating entries', async ()=>{
56
+ mockCache.get.mockResolvedValue([
57
+ 'cache-key-1'
58
+ ]);
59
+ await service.trackCacheKey('cache-key-1', 'product', mockCache);
60
+ expect(mockCache.set).toHaveBeenCalledWith('entity_product_keys', [
61
+ 'cache-key-1'
62
+ ]);
63
+ });
64
+ it('should append a new key alongside existing ones', async ()=>{
65
+ mockCache.get.mockResolvedValue([
66
+ 'cache-key-1'
67
+ ]);
68
+ await service.trackCacheKey('cache-key-2', 'product', mockCache);
69
+ expect(mockCache.set).toHaveBeenCalledWith('entity_product_keys', [
70
+ 'cache-key-1',
71
+ 'cache-key-2'
72
+ ]);
73
+ });
74
+ it('should scope the tracking key by entity id and tenant', async ()=>{
75
+ mockCache.get.mockResolvedValue(undefined);
76
+ await service.trackCacheKey('cache-key-1', 'product', mockCache, 'prod-1', 'tenant-a');
77
+ expect(mockCache.get).toHaveBeenCalledWith('tenant_tenant-a_entity_product_id_prod-1_keys');
78
+ expect(mockCache.set).toHaveBeenCalledWith('tenant_tenant-a_entity_product_id_prod-1_keys', [
79
+ 'cache-key-1'
80
+ ]);
81
+ });
82
+ it('should swallow cache read errors without throwing', async ()=>{
83
+ mockCache.get.mockRejectedValue(new Error('cache down'));
84
+ await expect(service.trackCacheKey('k', 'product', mockCache)).resolves.toBeUndefined();
85
+ expect(mockCache.set).not.toHaveBeenCalled();
86
+ });
87
+ it('should swallow cache write errors without throwing', async ()=>{
88
+ mockCache.get.mockResolvedValue([]);
89
+ mockCache.set.mockRejectedValue(new Error('cache down'));
90
+ await expect(service.trackCacheKey('k', 'product', mockCache)).resolves.toBeUndefined();
91
+ });
92
+ });
93
+ describe('clearCache', ()=>{
94
+ it('should delete every tracked key plus the tracking key itself', async ()=>{
95
+ mockCache.get.mockResolvedValue([
96
+ 'k1',
97
+ 'k2'
98
+ ]);
99
+ await service.clearCache('product', mockCache);
100
+ expect(mockCache.del).toHaveBeenCalledWith('k1');
101
+ expect(mockCache.del).toHaveBeenCalledWith('k2');
102
+ expect(mockCache.del).toHaveBeenCalledWith('entity_product_keys');
103
+ expect(mockCache.del).toHaveBeenCalledTimes(3);
104
+ });
105
+ it('should only delete the tracking key when no keys were tracked', async ()=>{
106
+ mockCache.get.mockResolvedValue(undefined);
107
+ await service.clearCache('product', mockCache);
108
+ expect(mockCache.del).toHaveBeenCalledTimes(1);
109
+ expect(mockCache.del).toHaveBeenCalledWith('entity_product_keys');
110
+ });
111
+ it('should continue deleting remaining keys even if one deletion rejects', async ()=>{
112
+ mockCache.get.mockResolvedValue([
113
+ 'k1',
114
+ 'k2'
115
+ ]);
116
+ mockCache.del.mockImplementation((key)=>key === 'k1' ? Promise.reject(new Error('fail')) : Promise.resolve());
117
+ await service.clearCache('product', mockCache);
118
+ expect(mockCache.del).toHaveBeenCalledWith('k2');
119
+ expect(mockCache.del).toHaveBeenCalledWith('entity_product_keys');
120
+ });
121
+ it('should scope deletion by entity id and tenant', async ()=>{
122
+ mockCache.get.mockResolvedValue([
123
+ 'k1'
124
+ ]);
125
+ await service.clearCache('product', mockCache, 'prod-1', 'tenant-a');
126
+ expect(mockCache.get).toHaveBeenCalledWith('tenant_tenant-a_entity_product_id_prod-1_keys');
127
+ });
128
+ it('should swallow errors from the initial cache read', async ()=>{
129
+ mockCache.get.mockRejectedValue(new Error('cache down'));
130
+ await expect(service.clearCache('product', mockCache)).resolves.toBeUndefined();
131
+ expect(mockCache.del).not.toHaveBeenCalled();
132
+ });
133
+ });
134
+ describe('transformToSlug', ()=>{
135
+ it('should lowercase and dash-separate a normal string', ()=>{
136
+ expect(service.transformToSlug('Hello World')).toBe('hello-world');
137
+ });
138
+ it('should collapse runs of non-alphanumeric characters into a single dash', ()=>{
139
+ expect(service.transformToSlug('Hello World!!!')).toBe('hello-world-');
140
+ });
141
+ it('should trim leading/trailing whitespace before slugging', ()=>{
142
+ expect(service.transformToSlug(' Hello World ')).toBe('hello-world');
143
+ });
144
+ it('should append a random numeric salt when requested', ()=>{
145
+ const randomSpy = jest.spyOn(service, 'getRandomInt').mockReturnValue(42);
146
+ expect(service.transformToSlug('Hello World', true)).toBe('hello-world-42');
147
+ randomSpy.mockRestore();
148
+ });
149
+ it('should handle an empty string', ()=>{
150
+ expect(service.transformToSlug('')).toBe('');
151
+ });
152
+ it('should handle strings that are entirely non-alphanumeric', ()=>{
153
+ expect(service.transformToSlug('!!!')).toBe('-');
154
+ });
155
+ });
156
+ describe('getRandomInt', ()=>{
157
+ it('should return the exact bound when min equals max', ()=>{
158
+ expect(service.getRandomInt(5, 5)).toBe(5);
159
+ });
160
+ it('should stay within an inclusive [min, max] range across many samples', ()=>{
161
+ for(let i = 0; i < 200; i++){
162
+ const value = service.getRandomInt(1, 10);
163
+ expect(value).toBeGreaterThanOrEqual(1);
164
+ expect(value).toBeLessThanOrEqual(10);
165
+ expect(Number.isInteger(value)).toBe(true);
166
+ }
167
+ });
168
+ });
169
+ });
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ const _datetimeutil = require("./date-time.util");
6
+ describe('date-time.util', ()=>{
7
+ describe('localToUtc', ()=>{
8
+ it('should convert a local date/time in a fixed-offset timezone to UTC', ()=>{
9
+ // Asia/Dhaka is UTC+6, no DST
10
+ const result = (0, _datetimeutil.localToUtc)('2026-01-15', '10:00', 'Asia/Dhaka');
11
+ expect(result.toISOString()).toBe('2026-01-15T04:00:00.000Z');
12
+ });
13
+ it('should convert local time in UTC timezone unchanged', ()=>{
14
+ const result = (0, _datetimeutil.localToUtc)('2026-06-01', '12:30', 'UTC');
15
+ expect(result.toISOString()).toBe('2026-06-01T12:30:00.000Z');
16
+ });
17
+ it('should handle a negative UTC offset timezone (America/New_York in winter, no DST)', ()=>{
18
+ // America/New_York is UTC-5 in January (standard time, no DST)
19
+ const result = (0, _datetimeutil.localToUtc)('2026-01-15', '09:00', 'America/New_York');
20
+ expect(result.toISOString()).toBe('2026-01-15T14:00:00.000Z');
21
+ });
22
+ it('should account for DST when converting a summer date in America/New_York (UTC-4)', ()=>{
23
+ const result = (0, _datetimeutil.localToUtc)('2026-07-15', '09:00', 'America/New_York');
24
+ expect(result.toISOString()).toBe('2026-07-15T13:00:00.000Z');
25
+ });
26
+ });
27
+ describe('utcToLocal', ()=>{
28
+ it('should convert a UTC Date to local date/time/display parts', ()=>{
29
+ const result = (0, _datetimeutil.utcToLocal)(new Date('2026-01-15T04:00:00.000Z'), 'Asia/Dhaka');
30
+ expect(result.date).toBe('2026-01-15');
31
+ expect(result.time).toBe('10:00');
32
+ expect(result.display).toEqual(expect.any(String));
33
+ });
34
+ it('should accept a UTC date string as input', ()=>{
35
+ const result = (0, _datetimeutil.utcToLocal)('2026-01-15T04:00:00.000Z', 'Asia/Dhaka');
36
+ expect(result.date).toBe('2026-01-15');
37
+ expect(result.time).toBe('10:00');
38
+ });
39
+ it('should normalize midnight (en-CA "24") to "00"', ()=>{
40
+ // 00:00 Dhaka time == 18:00 UTC the previous day
41
+ const result = (0, _datetimeutil.utcToLocal)('2026-01-14T18:00:00.000Z', 'Asia/Dhaka');
42
+ expect(result.date).toBe('2026-01-15');
43
+ expect(result.time).toBe('00:00');
44
+ });
45
+ });
46
+ describe('formatInTimezone', ()=>{
47
+ it('should format a date in the given timezone with default options', ()=>{
48
+ const result = (0, _datetimeutil.formatInTimezone)('2026-01-15T04:00:00.000Z', 'Asia/Dhaka');
49
+ expect(typeof result).toBe('string');
50
+ expect(result.length).toBeGreaterThan(0);
51
+ });
52
+ it('should respect custom Intl.DateTimeFormatOptions', ()=>{
53
+ const result = (0, _datetimeutil.formatInTimezone)('2026-01-15T04:00:00.000Z', 'UTC', {
54
+ year: 'numeric'
55
+ });
56
+ expect(result).toBe('2026');
57
+ });
58
+ it('should accept a Date object as input', ()=>{
59
+ const result = (0, _datetimeutil.formatInTimezone)(new Date('2026-01-15T04:00:00.000Z'), 'UTC', {
60
+ year: 'numeric'
61
+ });
62
+ expect(result).toBe('2026');
63
+ });
64
+ });
65
+ describe('getTodayInTimezone', ()=>{
66
+ it('should return a date string in YYYY-MM-DD format', ()=>{
67
+ const result = (0, _datetimeutil.getTodayInTimezone)('UTC');
68
+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/);
69
+ });
70
+ it('should match utcToLocal(now, timezone).date', ()=>{
71
+ const now = new Date();
72
+ const expected = (0, _datetimeutil.utcToLocal)(now, 'Asia/Dhaka').date;
73
+ expect((0, _datetimeutil.getTodayInTimezone)('Asia/Dhaka')).toBe(expected);
74
+ });
75
+ });
76
+ describe('round-trip', ()=>{
77
+ it('should round-trip localToUtc -> utcToLocal for a fixed-offset zone', ()=>{
78
+ const utc = (0, _datetimeutil.localToUtc)('2026-03-10', '08:15', 'Asia/Dhaka');
79
+ const back = (0, _datetimeutil.utcToLocal)(utc, 'Asia/Dhaka');
80
+ expect(back.date).toBe('2026-03-10');
81
+ expect(back.time).toBe('08:15');
82
+ });
83
+ });
84
+ });