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