@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,122 @@
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
+ function _ts_decorate(decorators, target, key, desc) {
15
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
18
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19
+ }
20
+ function _ts_metadata(k, v) {
21
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22
+ }
23
+ import 'reflect-metadata';
24
+ import { SingleResponseDto, ListResponseDto, BulkResponseDto } from '../dtos';
25
+ import { ApiResponseDto } from './api-response.decorator';
26
+ // @nestjs/swagger doesn't expose ./dist/constants via its package "exports" map,
27
+ // so the decorator metadata keys are mirrored here (see node_modules/@nestjs/swagger/dist/constants.js).
28
+ const SWAGGER_API_RESPONSE = 'swagger/apiResponse';
29
+ const SWAGGER_API_EXTRA_MODELS = 'swagger/apiExtraModels';
30
+ let SampleDto = class SampleDto {
31
+ constructor(){
32
+ _define_property(this, "id", void 0);
33
+ }
34
+ };
35
+ function getApiResponseSchema(target, methodName) {
36
+ const responses = Reflect.getMetadata(SWAGGER_API_RESPONSE, target[methodName]);
37
+ // ApiOkResponse stores under status code 200
38
+ return responses?.[200]?.schema ?? responses?.['200']?.schema;
39
+ }
40
+ describe('ApiResponseDto', ()=>{
41
+ it('should wrap a single response in SingleResponseDto by default', ()=>{
42
+ let Controller = class Controller {
43
+ handler() {}
44
+ };
45
+ _ts_decorate([
46
+ ApiResponseDto(SampleDto),
47
+ _ts_metadata("design:type", Function),
48
+ _ts_metadata("design:paramtypes", []),
49
+ _ts_metadata("design:returntype", void 0)
50
+ ], Controller.prototype, "handler", null);
51
+ const schema = getApiResponseSchema(Controller.prototype, 'handler');
52
+ expect(schema.allOf[0].$ref).toContain(SingleResponseDto.name);
53
+ expect(schema.allOf[1].properties.data.$ref).toContain(SampleDto.name);
54
+ expect(schema.allOf[1].properties.meta).toBeUndefined();
55
+ });
56
+ it('should wrap a list response with pagination meta when isArray + list', ()=>{
57
+ let Controller = class Controller {
58
+ handler() {}
59
+ };
60
+ _ts_decorate([
61
+ ApiResponseDto(SampleDto, true, 'list'),
62
+ _ts_metadata("design:type", Function),
63
+ _ts_metadata("design:paramtypes", []),
64
+ _ts_metadata("design:returntype", void 0)
65
+ ], Controller.prototype, "handler", null);
66
+ const schema = getApiResponseSchema(Controller.prototype, 'handler');
67
+ expect(schema.allOf[0].$ref).toContain(ListResponseDto.name);
68
+ expect(schema.allOf[1].properties.data.type).toBe('array');
69
+ expect(schema.allOf[1].properties.data.items.$ref).toContain(SampleDto.name);
70
+ expect(schema.allOf[1].properties.meta.$ref).toBeDefined();
71
+ });
72
+ it('should wrap a bulk response with bulk meta when isArray + bulk', ()=>{
73
+ let Controller = class Controller {
74
+ handler() {}
75
+ };
76
+ _ts_decorate([
77
+ ApiResponseDto(SampleDto, true, 'bulk'),
78
+ _ts_metadata("design:type", Function),
79
+ _ts_metadata("design:paramtypes", []),
80
+ _ts_metadata("design:returntype", void 0)
81
+ ], Controller.prototype, "handler", null);
82
+ const schema = getApiResponseSchema(Controller.prototype, 'handler');
83
+ expect(schema.allOf[0].$ref).toContain(BulkResponseDto.name);
84
+ expect(schema.allOf[1].properties.data.type).toBe('array');
85
+ expect(schema.allOf[1].properties.meta.$ref).toBeDefined();
86
+ });
87
+ it('should use SingleResponseDto when isArray is true but arrayType is "single"', ()=>{
88
+ let Controller = class Controller {
89
+ handler() {}
90
+ };
91
+ _ts_decorate([
92
+ ApiResponseDto(SampleDto, true, 'single'),
93
+ _ts_metadata("design:type", Function),
94
+ _ts_metadata("design:paramtypes", []),
95
+ _ts_metadata("design:returntype", void 0)
96
+ ], Controller.prototype, "handler", null);
97
+ const schema = getApiResponseSchema(Controller.prototype, 'handler');
98
+ expect(schema.allOf[0].$ref).toContain(SingleResponseDto.name);
99
+ // NOTE: data schema stays array-shaped here because `isArray` (not `arrayType`) drives it —
100
+ // arrayType only controls which wrapper/meta DTO is chosen.
101
+ expect(schema.allOf[1].properties.data.type).toBe('array');
102
+ expect(schema.allOf[1].properties.data.items.$ref).toContain(SampleDto.name);
103
+ });
104
+ it('should register extra models including the wrapper DTOs and the given DTO', ()=>{
105
+ let Controller = class Controller {
106
+ handler() {}
107
+ };
108
+ _ts_decorate([
109
+ ApiResponseDto(SampleDto),
110
+ _ts_metadata("design:type", Function),
111
+ _ts_metadata("design:paramtypes", []),
112
+ _ts_metadata("design:returntype", void 0)
113
+ ], Controller.prototype, "handler", null);
114
+ const extraModels = Reflect.getMetadata(SWAGGER_API_EXTRA_MODELS, Controller.prototype.handler);
115
+ expect(extraModels).toEqual(expect.arrayContaining([
116
+ SingleResponseDto,
117
+ ListResponseDto,
118
+ BulkResponseDto,
119
+ SampleDto
120
+ ]));
121
+ });
122
+ });
@@ -0,0 +1,73 @@
1
+ function _ts_decorate(decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ }
7
+ function _ts_metadata(k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ }
10
+ function _ts_param(paramIndex, decorator) {
11
+ return function(target, key) {
12
+ decorator(target, key, paramIndex);
13
+ };
14
+ }
15
+ import { buildMockUser } from '@test-utils/mocks/logged-user.mock';
16
+ // createParamDecorator wraps the factory; the underlying factory is invoked via
17
+ // the ROUTE_ARGS_METADATA internals. We extract it directly to unit-test the logic
18
+ // without mounting a full controller/route.
19
+ import { CurrentUser } from './current-user.decorator';
20
+ function getParamDecoratorFactory(decorator) {
21
+ let Test = class Test {
22
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
23
+ test(_value) {
24
+ /* noop */ }
25
+ };
26
+ _ts_decorate([
27
+ _ts_param(0, decorator()),
28
+ _ts_metadata("design:type", Function),
29
+ _ts_metadata("design:paramtypes", [
30
+ Object
31
+ ]),
32
+ _ts_metadata("design:returntype", void 0)
33
+ ], Test.prototype, "test", null);
34
+ const args = Reflect.getMetadata('__routeArguments__', Test, 'test');
35
+ const [firstParam] = Object.values(args);
36
+ return firstParam.factory;
37
+ }
38
+ function buildContext(request) {
39
+ return {
40
+ switchToHttp: ()=>({
41
+ getRequest: ()=>request
42
+ })
43
+ };
44
+ }
45
+ describe('CurrentUser', ()=>{
46
+ const factory = getParamDecoratorFactory(CurrentUser);
47
+ it('should return the entire user object when called without data', ()=>{
48
+ const user = buildMockUser();
49
+ const ctx = buildContext({
50
+ user
51
+ });
52
+ expect(factory(undefined, ctx)).toBe(user);
53
+ });
54
+ it('should return a specific property when data is provided', ()=>{
55
+ const user = buildMockUser({
56
+ email: 'specific@example.com'
57
+ });
58
+ const ctx = buildContext({
59
+ user
60
+ });
61
+ expect(factory('email', ctx)).toBe('specific@example.com');
62
+ });
63
+ it('should return undefined when requesting a property from a null user', ()=>{
64
+ const ctx = buildContext({
65
+ user: null
66
+ });
67
+ expect(factory('email', ctx)).toBeUndefined();
68
+ });
69
+ it('should return undefined for the whole user when request.user is undefined', ()=>{
70
+ const ctx = buildContext({});
71
+ expect(factory(undefined, ctx)).toBeUndefined();
72
+ });
73
+ });
@@ -0,0 +1,349 @@
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
+ function _ts_decorate(decorators, target, key, desc) {
15
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
18
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19
+ }
20
+ function _ts_metadata(k, v) {
21
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22
+ }
23
+ import { Logger } from '@nestjs/common';
24
+ const mockWinstonLogger = {
25
+ log: jest.fn(),
26
+ error: jest.fn()
27
+ };
28
+ const createModuleLoggerMock = jest.fn((..._args)=>mockWinstonLogger);
29
+ jest.mock('../classes/winston.logger.class', ()=>({
30
+ createModuleLogger: (...args)=>createModuleLoggerMock(...args)
31
+ }));
32
+ const getRequestIdMock = jest.fn(()=>'req-1');
33
+ const getUserIdMock = jest.fn(()=>'user-1');
34
+ const getTenantIdMock = jest.fn(()=>'tenant-1');
35
+ const getCompanyIdMock = jest.fn(()=>'company-1');
36
+ jest.mock('../middlewares/logger.middleware', ()=>({
37
+ getRequestId: ()=>getRequestIdMock(),
38
+ getUserId: ()=>getUserIdMock(),
39
+ getTenantId: ()=>getTenantIdMock(),
40
+ getCompanyId: ()=>getCompanyIdMock()
41
+ }));
42
+ import { LogAction } from './log-action.decorator';
43
+ describe('LogAction', ()=>{
44
+ let nestLoggerWarnSpy;
45
+ let nestLoggerDebugSpy;
46
+ let nestLoggerErrorSpy;
47
+ beforeEach(()=>{
48
+ jest.clearAllMocks();
49
+ nestLoggerWarnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation(()=>undefined);
50
+ nestLoggerDebugSpy = jest.spyOn(Logger.prototype, 'debug').mockImplementation(()=>undefined);
51
+ nestLoggerErrorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(()=>undefined);
52
+ });
53
+ afterEach(()=>{
54
+ jest.restoreAllMocks();
55
+ });
56
+ describe('using the Nest Logger (no moduleName)', ()=>{
57
+ let Service = class Service {
58
+ async doWork(value) {
59
+ return `done:${value}`;
60
+ }
61
+ async fail() {
62
+ throw new Error('boom');
63
+ }
64
+ constructor(){
65
+ _define_property(this, "entityName", 'product');
66
+ }
67
+ };
68
+ _ts_decorate([
69
+ LogAction(),
70
+ _ts_metadata("design:type", Function),
71
+ _ts_metadata("design:paramtypes", [
72
+ String
73
+ ]),
74
+ _ts_metadata("design:returntype", Promise)
75
+ ], Service.prototype, "doWork", null);
76
+ _ts_decorate([
77
+ LogAction(),
78
+ _ts_metadata("design:type", Function),
79
+ _ts_metadata("design:paramtypes", []),
80
+ _ts_metadata("design:returntype", Promise)
81
+ ], Service.prototype, "fail", null);
82
+ it('should log a debug start/success message and return the original result', async ()=>{
83
+ const service = new Service();
84
+ const result = await service.doWork('x');
85
+ expect(result).toBe('done:x');
86
+ expect(nestLoggerDebugSpy).toHaveBeenCalledTimes(2);
87
+ const [startMessage] = nestLoggerDebugSpy.mock.calls[0];
88
+ expect(startMessage).toContain('Executing action method "product.doWork"');
89
+ const [successMessage] = nestLoggerDebugSpy.mock.calls[1];
90
+ expect(successMessage).toContain('Executed action method "product.doWork"');
91
+ });
92
+ it('should log and rethrow the original error on failure', async ()=>{
93
+ const service = new Service();
94
+ await expect(service.fail()).rejects.toThrow('boom');
95
+ expect(nestLoggerErrorSpy).toHaveBeenCalledTimes(1);
96
+ const [message, stack] = nestLoggerErrorSpy.mock.calls[0];
97
+ expect(message).toContain('Failed action method "product.fail"');
98
+ expect(message).toContain('boom');
99
+ expect(stack).toEqual(expect.any(String));
100
+ });
101
+ });
102
+ describe('using the Winston module logger (moduleName resolved from instance property)', ()=>{
103
+ let Service = class Service {
104
+ async doWork() {
105
+ return {
106
+ id: '1'
107
+ };
108
+ }
109
+ constructor(){
110
+ _define_property(this, "entityName", 'product');
111
+ _define_property(this, "moduleName", 'catalog');
112
+ }
113
+ };
114
+ _ts_decorate([
115
+ LogAction(),
116
+ _ts_metadata("design:type", Function),
117
+ _ts_metadata("design:paramtypes", []),
118
+ _ts_metadata("design:returntype", Promise)
119
+ ], Service.prototype, "doWork", null);
120
+ it('should resolve the module logger via createModuleLogger(moduleName)', async ()=>{
121
+ const service = new Service();
122
+ await service.doWork();
123
+ expect(createModuleLoggerMock).toHaveBeenCalledWith('catalog');
124
+ expect(mockWinstonLogger.log).toHaveBeenCalledTimes(2);
125
+ });
126
+ });
127
+ describe('options', ()=>{
128
+ it('should use a custom action name when provided', async ()=>{
129
+ let Service = class Service {
130
+ async doWork() {
131
+ return 'ok';
132
+ }
133
+ };
134
+ _ts_decorate([
135
+ LogAction({
136
+ action: 'custom.action'
137
+ }),
138
+ _ts_metadata("design:type", Function),
139
+ _ts_metadata("design:paramtypes", []),
140
+ _ts_metadata("design:returntype", Promise)
141
+ ], Service.prototype, "doWork", null);
142
+ await new Service().doWork();
143
+ const [startMessage] = nestLoggerDebugSpy.mock.calls[0];
144
+ expect(startMessage).toContain('"custom.action"');
145
+ });
146
+ it('should prefer decorator module option over instance moduleName', async ()=>{
147
+ let Service = class Service {
148
+ async doWork() {
149
+ return 'ok';
150
+ }
151
+ constructor(){
152
+ _define_property(this, "moduleName", 'instance-module');
153
+ }
154
+ };
155
+ _ts_decorate([
156
+ LogAction({
157
+ module: 'decorator-module'
158
+ }),
159
+ _ts_metadata("design:type", Function),
160
+ _ts_metadata("design:paramtypes", []),
161
+ _ts_metadata("design:returntype", Promise)
162
+ ], Service.prototype, "doWork", null);
163
+ await new Service().doWork();
164
+ expect(createModuleLoggerMock).toHaveBeenCalledWith('decorator-module');
165
+ });
166
+ it('should use the custom logLevel', async ()=>{
167
+ let Service = class Service {
168
+ async doWork() {
169
+ return 'ok';
170
+ }
171
+ };
172
+ _ts_decorate([
173
+ LogAction({
174
+ logLevel: 'warn'
175
+ }),
176
+ _ts_metadata("design:type", Function),
177
+ _ts_metadata("design:paramtypes", []),
178
+ _ts_metadata("design:returntype", Promise)
179
+ ], Service.prototype, "doWork", null);
180
+ await new Service().doWork();
181
+ // logLevel routes to the matching Logger method (nestLogger.warn), not nestLogger.log
182
+ expect(nestLoggerWarnSpy).toHaveBeenCalledTimes(2);
183
+ expect(nestLoggerDebugSpy).not.toHaveBeenCalled();
184
+ });
185
+ it('should redact sensitive keys from params when includeParams is true', async ()=>{
186
+ let Service = class Service {
187
+ async doWork(_dto) {
188
+ return 'ok';
189
+ }
190
+ };
191
+ _ts_decorate([
192
+ LogAction({
193
+ includeParams: true
194
+ }),
195
+ _ts_metadata("design:type", Function),
196
+ _ts_metadata("design:paramtypes", [
197
+ typeof Record === "undefined" ? Object : Record
198
+ ]),
199
+ _ts_metadata("design:returntype", Promise)
200
+ ], Service.prototype, "doWork", null);
201
+ await new Service().doWork({
202
+ email: 'a@b.com',
203
+ password: 'secret',
204
+ token: 'abc'
205
+ });
206
+ const [, startContext] = nestLoggerDebugSpy.mock.calls[0];
207
+ expect(startContext.params[0]).toEqual({
208
+ email: 'a@b.com',
209
+ password: '[REDACTED]',
210
+ token: '[REDACTED]'
211
+ });
212
+ });
213
+ it('should pass through null/undefined/primitive args unchanged when sanitizing params', async ()=>{
214
+ let Service = class Service {
215
+ async doWork(_a, _b, _c) {
216
+ return 'ok';
217
+ }
218
+ };
219
+ _ts_decorate([
220
+ LogAction({
221
+ includeParams: true
222
+ }),
223
+ _ts_metadata("design:type", Function),
224
+ _ts_metadata("design:paramtypes", [
225
+ Object,
226
+ Object,
227
+ Object
228
+ ]),
229
+ _ts_metadata("design:returntype", Promise)
230
+ ], Service.prototype, "doWork", null);
231
+ await new Service().doWork(null, undefined, 'plain-string');
232
+ const [, startContext] = nestLoggerDebugSpy.mock.calls[0];
233
+ expect(startContext.params).toEqual([
234
+ null,
235
+ undefined,
236
+ 'plain-string'
237
+ ]);
238
+ });
239
+ it('should include a result preview when includeResult is true and result is an array', async ()=>{
240
+ let Service = class Service {
241
+ async doWork() {
242
+ return [
243
+ 1,
244
+ 2,
245
+ 3
246
+ ];
247
+ }
248
+ };
249
+ _ts_decorate([
250
+ LogAction({
251
+ includeResult: true
252
+ }),
253
+ _ts_metadata("design:type", Function),
254
+ _ts_metadata("design:paramtypes", []),
255
+ _ts_metadata("design:returntype", Promise)
256
+ ], Service.prototype, "doWork", null);
257
+ await new Service().doWork();
258
+ const [, successContext] = nestLoggerDebugSpy.mock.calls[1];
259
+ expect(successContext.resultType).toBe('Array<3 items>');
260
+ expect(successContext.resultPreview).toEqual({
261
+ count: 3,
262
+ sample: [
263
+ 1,
264
+ 2
265
+ ]
266
+ });
267
+ });
268
+ it('should include a keys-preview when includeResult is true and result is an object', async ()=>{
269
+ let Service = class Service {
270
+ async doWork() {
271
+ return {
272
+ a: 1,
273
+ b: 2,
274
+ c: 3,
275
+ d: 4,
276
+ e: 5,
277
+ f: 6
278
+ };
279
+ }
280
+ };
281
+ _ts_decorate([
282
+ LogAction({
283
+ includeResult: true
284
+ }),
285
+ _ts_metadata("design:type", Function),
286
+ _ts_metadata("design:paramtypes", []),
287
+ _ts_metadata("design:returntype", Promise)
288
+ ], Service.prototype, "doWork", null);
289
+ await new Service().doWork();
290
+ const [, successContext] = nestLoggerDebugSpy.mock.calls[1];
291
+ expect(successContext.resultPreview).toEqual({
292
+ keys: [
293
+ 'a',
294
+ 'b',
295
+ 'c',
296
+ 'd',
297
+ 'e',
298
+ 'f'
299
+ ].slice(0, 5),
300
+ hasMore: true
301
+ });
302
+ });
303
+ it('should not attach a result preview when includeResult is false', async ()=>{
304
+ let Service = class Service {
305
+ async doWork() {
306
+ return {
307
+ a: 1
308
+ };
309
+ }
310
+ };
311
+ _ts_decorate([
312
+ LogAction(),
313
+ _ts_metadata("design:type", Function),
314
+ _ts_metadata("design:paramtypes", []),
315
+ _ts_metadata("design:returntype", Promise)
316
+ ], Service.prototype, "doWork", null);
317
+ await new Service().doWork();
318
+ const [, successContext] = nestLoggerDebugSpy.mock.calls[1];
319
+ expect(successContext.resultPreview).toBeUndefined();
320
+ });
321
+ it('should report resultType "null" and "undefined" correctly', async ()=>{
322
+ let Service = class Service {
323
+ async returnsNull() {
324
+ return null;
325
+ }
326
+ async returnsUndefined() {
327
+ return undefined;
328
+ }
329
+ };
330
+ _ts_decorate([
331
+ LogAction(),
332
+ _ts_metadata("design:type", Function),
333
+ _ts_metadata("design:paramtypes", []),
334
+ _ts_metadata("design:returntype", Promise)
335
+ ], Service.prototype, "returnsNull", null);
336
+ _ts_decorate([
337
+ LogAction(),
338
+ _ts_metadata("design:type", Function),
339
+ _ts_metadata("design:paramtypes", []),
340
+ _ts_metadata("design:returntype", Promise)
341
+ ], Service.prototype, "returnsUndefined", null);
342
+ const service = new Service();
343
+ await service.returnsNull();
344
+ await service.returnsUndefined();
345
+ expect(nestLoggerDebugSpy.mock.calls[1][1].resultType).toBe('null');
346
+ expect(nestLoggerDebugSpy.mock.calls[3][1].resultType).toBe('undefined');
347
+ });
348
+ });
349
+ });
@@ -0,0 +1,46 @@
1
+ function _ts_decorate(decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ }
7
+ function _ts_metadata(k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ }
10
+ import { Reflector } from '@nestjs/core';
11
+ import { IS_PUBLIC_KEY } from '../constants';
12
+ import { Public } from './public.decorator';
13
+ describe('Public', ()=>{
14
+ it('should set the IS_PUBLIC_KEY metadata to true on a method', ()=>{
15
+ let TestController = class TestController {
16
+ handler() {}
17
+ };
18
+ _ts_decorate([
19
+ Public(),
20
+ _ts_metadata("design:type", Function),
21
+ _ts_metadata("design:paramtypes", []),
22
+ _ts_metadata("design:returntype", void 0)
23
+ ], TestController.prototype, "handler", null);
24
+ const reflector = new Reflector();
25
+ const metadata = reflector.get(IS_PUBLIC_KEY, TestController.prototype.handler);
26
+ expect(metadata).toBe(true);
27
+ });
28
+ it('should set the IS_PUBLIC_KEY metadata to true on a class', ()=>{
29
+ let TestController = class TestController {
30
+ };
31
+ TestController = _ts_decorate([
32
+ Public()
33
+ ], TestController);
34
+ const reflector = new Reflector();
35
+ const metadata = reflector.get(IS_PUBLIC_KEY, TestController);
36
+ expect(metadata).toBe(true);
37
+ });
38
+ it('should not set metadata on a handler that does not use the decorator', ()=>{
39
+ let TestController = class TestController {
40
+ handler() {}
41
+ };
42
+ const reflector = new Reflector();
43
+ const metadata = reflector.get(IS_PUBLIC_KEY, TestController.prototype.handler);
44
+ expect(metadata).toBeUndefined();
45
+ });
46
+ });