@dismissible/nestjs-api 0.0.2-canary.5daf195.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 (52) hide show
  1. package/config/.env.yaml +41 -0
  2. package/jest.config.ts +35 -0
  3. package/jest.e2e-config.ts +13 -0
  4. package/nest-cli.json +16 -0
  5. package/package.json +58 -0
  6. package/project.json +94 -0
  7. package/scripts/performance-test.config.json +29 -0
  8. package/scripts/performance-test.ts +845 -0
  9. package/src/app-test.factory.ts +39 -0
  10. package/src/app.module.ts +60 -0
  11. package/src/app.setup.ts +52 -0
  12. package/src/bootstrap.ts +29 -0
  13. package/src/config/app.config.spec.ts +117 -0
  14. package/src/config/app.config.ts +20 -0
  15. package/src/config/config.module.spec.ts +94 -0
  16. package/src/config/config.module.ts +50 -0
  17. package/src/config/default-app.config.spec.ts +74 -0
  18. package/src/config/default-app.config.ts +24 -0
  19. package/src/config/index.ts +2 -0
  20. package/src/cors/cors.config.spec.ts +162 -0
  21. package/src/cors/cors.config.ts +37 -0
  22. package/src/cors/index.ts +1 -0
  23. package/src/health/health.controller.spec.ts +24 -0
  24. package/src/health/health.controller.ts +16 -0
  25. package/src/health/health.module.ts +9 -0
  26. package/src/health/index.ts +2 -0
  27. package/src/helmet/helmet.config.spec.ts +197 -0
  28. package/src/helmet/helmet.config.ts +60 -0
  29. package/src/helmet/index.ts +1 -0
  30. package/src/index.ts +5 -0
  31. package/src/main.ts +3 -0
  32. package/src/server/index.ts +1 -0
  33. package/src/server/server.config.spec.ts +65 -0
  34. package/src/server/server.config.ts +8 -0
  35. package/src/swagger/index.ts +2 -0
  36. package/src/swagger/swagger.config.spec.ts +113 -0
  37. package/src/swagger/swagger.config.ts +12 -0
  38. package/src/swagger/swagger.factory.spec.ts +125 -0
  39. package/src/swagger/swagger.factory.ts +24 -0
  40. package/src/validation/index.ts +1 -0
  41. package/src/validation/validation.config.ts +47 -0
  42. package/test/config/.env.yaml +23 -0
  43. package/test/config-jwt-auth/.env.yaml +26 -0
  44. package/test/dismiss.e2e-spec.ts +61 -0
  45. package/test/full-cycle.e2e-spec.ts +55 -0
  46. package/test/get-or-create.e2e-spec.ts +51 -0
  47. package/test/jwt-auth.e2e-spec.ts +335 -0
  48. package/test/restore.e2e-spec.ts +61 -0
  49. package/tsconfig.app.json +13 -0
  50. package/tsconfig.e2e.json +12 -0
  51. package/tsconfig.json +13 -0
  52. package/tsconfig.spec.json +12 -0
@@ -0,0 +1,113 @@
1
+ import 'reflect-metadata';
2
+ import { plainToInstance } from 'class-transformer';
3
+ import { validate } from 'class-validator';
4
+ import { SwaggerConfig } from './swagger.config';
5
+
6
+ describe('SwaggerConfig', () => {
7
+ describe('enabled', () => {
8
+ it('should transform string "true" to boolean true', () => {
9
+ const config = plainToInstance(SwaggerConfig, { enabled: 'true' });
10
+ expect(config.enabled).toBe(true);
11
+ });
12
+
13
+ it('should transform string "false" to boolean false', () => {
14
+ const config = plainToInstance(SwaggerConfig, { enabled: 'false' });
15
+ expect(config.enabled).toBe(false);
16
+ });
17
+
18
+ it('should keep boolean true as true', () => {
19
+ const config = plainToInstance(SwaggerConfig, { enabled: true });
20
+ expect(config.enabled).toBe(true);
21
+ });
22
+
23
+ it('should keep boolean false as false', () => {
24
+ const config = plainToInstance(SwaggerConfig, { enabled: false });
25
+ expect(config.enabled).toBe(false);
26
+ });
27
+
28
+ it('should transform other string values to false', () => {
29
+ const config = plainToInstance(SwaggerConfig, { enabled: 'yes' });
30
+ expect(config.enabled).toBe(false);
31
+ });
32
+
33
+ it('should handle case-insensitive "true"', () => {
34
+ const config = plainToInstance(SwaggerConfig, { enabled: 'TRUE' });
35
+ expect(config.enabled).toBe(true);
36
+ });
37
+
38
+ it('should handle case-insensitive "True"', () => {
39
+ const config = plainToInstance(SwaggerConfig, { enabled: 'True' });
40
+ expect(config.enabled).toBe(true);
41
+ });
42
+ });
43
+
44
+ describe('path', () => {
45
+ it('should accept string path', () => {
46
+ const config = plainToInstance(SwaggerConfig, {
47
+ enabled: true,
48
+ path: 'api-docs',
49
+ });
50
+ expect(config.path).toBe('api-docs');
51
+ });
52
+
53
+ it('should allow path to be optional', () => {
54
+ const config = plainToInstance(SwaggerConfig, { enabled: true });
55
+ expect(config.path).toBeUndefined();
56
+ });
57
+ });
58
+
59
+ describe('validation', () => {
60
+ it('should pass validation with valid config', async () => {
61
+ const config = plainToInstance(SwaggerConfig, {
62
+ enabled: true,
63
+ path: 'docs',
64
+ });
65
+ const errors = await validate(config);
66
+ expect(errors).toHaveLength(0);
67
+ });
68
+
69
+ it('should pass validation with only required fields', async () => {
70
+ const config = plainToInstance(SwaggerConfig, { enabled: true });
71
+ const errors = await validate(config);
72
+ expect(errors).toHaveLength(0);
73
+ });
74
+
75
+ it('should pass validation when enabled is transformed from string', async () => {
76
+ const config = plainToInstance(SwaggerConfig, { enabled: 'true' });
77
+ const errors = await validate(config);
78
+ expect(errors).toHaveLength(0);
79
+ });
80
+
81
+ it('should fail validation when enabled is missing', async () => {
82
+ const config = plainToInstance(SwaggerConfig, {});
83
+ const errors = await validate(config);
84
+ expect(errors.length).toBeGreaterThan(0);
85
+ expect(errors[0].property).toBe('enabled');
86
+ });
87
+
88
+ it('should fail validation when enabled is null', async () => {
89
+ const config = plainToInstance(SwaggerConfig, { enabled: null });
90
+ const errors = await validate(config);
91
+ expect(errors.length).toBeGreaterThan(0);
92
+ expect(errors[0].property).toBe('enabled');
93
+ });
94
+
95
+ it('should fail validation when enabled is undefined', async () => {
96
+ const config = plainToInstance(SwaggerConfig, { enabled: undefined });
97
+ const errors = await validate(config);
98
+ expect(errors.length).toBeGreaterThan(0);
99
+ expect(errors[0].property).toBe('enabled');
100
+ });
101
+
102
+ it('should fail validation when path is not a string', async () => {
103
+ const config = plainToInstance(SwaggerConfig, {
104
+ enabled: true,
105
+ path: 123,
106
+ });
107
+ const errors = await validate(config);
108
+ expect(errors.length).toBeGreaterThan(0);
109
+ const pathError = errors.find((e) => e.property === 'path');
110
+ expect(pathError).toBeDefined();
111
+ });
112
+ });
113
+ });
@@ -0,0 +1,12 @@
1
+ import { IsBoolean, IsOptional, IsString } from 'class-validator';
2
+ import { TransformBoolean } from '@dismissible/nestjs-validation';
3
+
4
+ export class SwaggerConfig {
5
+ @IsBoolean()
6
+ @TransformBoolean()
7
+ public readonly enabled!: boolean;
8
+
9
+ @IsString()
10
+ @IsOptional()
11
+ public readonly path?: string;
12
+ }
@@ -0,0 +1,125 @@
1
+ import { INestApplication } from '@nestjs/common';
2
+ import { DocumentBuilder } from '@nestjs/swagger';
3
+ import { configureAppWithSwagger } from './swagger.factory';
4
+ import { SwaggerConfig } from './swagger.config';
5
+
6
+ const mockCreateDocument = jest.fn();
7
+ const mockSetup = jest.fn();
8
+ const mockSetTitle = jest.fn().mockReturnThis();
9
+ const mockSetDescription = jest.fn().mockReturnThis();
10
+ const mockSetVersion = jest.fn().mockReturnThis();
11
+ const mockBuild = jest.fn().mockReturnValue({});
12
+
13
+ jest.mock('@nestjs/swagger', () => ({
14
+ SwaggerModule: {
15
+ createDocument: (...args: any[]) => mockCreateDocument(...args),
16
+ setup: (...args: any[]) => mockSetup(...args),
17
+ },
18
+ DocumentBuilder: jest.fn().mockImplementation(() => ({
19
+ setTitle: mockSetTitle,
20
+ setDescription: mockSetDescription,
21
+ setVersion: mockSetVersion,
22
+ build: mockBuild,
23
+ })),
24
+ }));
25
+
26
+ describe('configureAppWithSwagger', () => {
27
+ let mockApp: jest.Mocked<INestApplication>;
28
+
29
+ beforeEach(() => {
30
+ jest.clearAllMocks();
31
+ mockApp = {} as any;
32
+ });
33
+
34
+ it('should configure Swagger when enabled is true', () => {
35
+ const swaggerConfig: SwaggerConfig = {
36
+ enabled: true,
37
+ path: 'docs',
38
+ };
39
+
40
+ configureAppWithSwagger(mockApp, swaggerConfig);
41
+
42
+ expect(DocumentBuilder).toHaveBeenCalled();
43
+ expect(mockSetTitle).toHaveBeenCalledWith('Dismissible');
44
+ expect(mockSetDescription).toHaveBeenCalledWith('An API to handle dismissible items for users');
45
+ expect(mockSetVersion).toHaveBeenCalledWith('1.0');
46
+ expect(mockBuild).toHaveBeenCalled();
47
+ expect(mockSetup).toHaveBeenCalledWith('docs', mockApp, expect.any(Function), {
48
+ useGlobalPrefix: true,
49
+ });
50
+ });
51
+
52
+ it('should use default path "docs" when path is not provided', () => {
53
+ const swaggerConfig: SwaggerConfig = {
54
+ enabled: true,
55
+ };
56
+
57
+ configureAppWithSwagger(mockApp, swaggerConfig);
58
+
59
+ expect(mockSetup).toHaveBeenCalledWith('docs', mockApp, expect.any(Function), {
60
+ useGlobalPrefix: true,
61
+ });
62
+ });
63
+
64
+ it('should use custom path when provided', () => {
65
+ const swaggerConfig: SwaggerConfig = {
66
+ enabled: true,
67
+ path: 'api-docs',
68
+ };
69
+
70
+ configureAppWithSwagger(mockApp, swaggerConfig);
71
+
72
+ expect(mockSetup).toHaveBeenCalledWith('api-docs', mockApp, expect.any(Function), {
73
+ useGlobalPrefix: true,
74
+ });
75
+ });
76
+
77
+ it('should not configure Swagger when enabled is false', () => {
78
+ const swaggerConfig: SwaggerConfig = {
79
+ enabled: false,
80
+ };
81
+
82
+ configureAppWithSwagger(mockApp, swaggerConfig);
83
+
84
+ expect(DocumentBuilder).not.toHaveBeenCalled();
85
+ expect(mockSetup).not.toHaveBeenCalled();
86
+ });
87
+
88
+ it('should create document with correct operationIdFactory', () => {
89
+ const swaggerConfig: SwaggerConfig = {
90
+ enabled: true,
91
+ };
92
+
93
+ configureAppWithSwagger(mockApp, swaggerConfig);
94
+
95
+ const setupCall = mockSetup.mock.calls[0];
96
+ const documentFactory = setupCall[2];
97
+ documentFactory();
98
+
99
+ expect(mockCreateDocument).toHaveBeenCalledWith(
100
+ mockApp,
101
+ {},
102
+ expect.objectContaining({
103
+ operationIdFactory: expect.any(Function),
104
+ }),
105
+ );
106
+ });
107
+
108
+ it('should use methodKey as operationId', () => {
109
+ const swaggerConfig: SwaggerConfig = {
110
+ enabled: true,
111
+ };
112
+
113
+ configureAppWithSwagger(mockApp, swaggerConfig);
114
+
115
+ const setupCall = mockSetup.mock.calls[0];
116
+ const documentFactory = setupCall[2];
117
+ documentFactory();
118
+
119
+ const createDocumentCall = mockCreateDocument.mock.calls[0];
120
+ const operationIdFactory = createDocumentCall[2].operationIdFactory;
121
+
122
+ expect(operationIdFactory('UserController', 'createUser')).toBe('createUser');
123
+ expect(operationIdFactory('ItemController', 'getItem')).toBe('getItem');
124
+ });
125
+ });
@@ -0,0 +1,24 @@
1
+ import { INestApplication } from '@nestjs/common';
2
+ import { DocumentBuilder, SwaggerDocumentOptions, SwaggerModule } from '@nestjs/swagger';
3
+ import { SwaggerConfig } from './swagger.config';
4
+
5
+ const swaggerDocumentOptions: SwaggerDocumentOptions = {
6
+ operationIdFactory: (_controllerKey: string, methodKey: string) => methodKey,
7
+ };
8
+
9
+ export function configureAppWithSwagger(app: INestApplication, swaggerConfig: SwaggerConfig) {
10
+ if (swaggerConfig.enabled) {
11
+ const { path = 'docs' } = swaggerConfig;
12
+
13
+ const config = new DocumentBuilder()
14
+ .setTitle('Dismissible')
15
+ .setDescription('An API to handle dismissible items for users')
16
+ .setVersion('1.0')
17
+ .build();
18
+
19
+ const documentFactory = () => SwaggerModule.createDocument(app, config, swaggerDocumentOptions);
20
+ SwaggerModule.setup(path, app, documentFactory, {
21
+ useGlobalPrefix: true,
22
+ });
23
+ }
24
+ }
@@ -0,0 +1 @@
1
+ export * from './validation.config';
@@ -0,0 +1,47 @@
1
+ import { IsBoolean, IsOptional } from 'class-validator';
2
+ import { TransformBoolean } from '@dismissible/nestjs-validation';
3
+
4
+ /**
5
+ * Configuration for NestJS ValidationPipe
6
+ * @see https://docs.nestjs.com/techniques/validation
7
+ */
8
+ export class ValidationConfig {
9
+ /**
10
+ * Whether to disable error messages in validation responses.
11
+ * Should be true in production to prevent information disclosure.
12
+ * @default true in production, false in development
13
+ */
14
+ @IsBoolean()
15
+ @IsOptional()
16
+ @TransformBoolean()
17
+ public readonly disableErrorMessages?: boolean;
18
+
19
+ /**
20
+ * If set to true, validator will strip validated (returned) object of any properties
21
+ * that do not use any validation decorators.
22
+ * @default true
23
+ */
24
+ @IsBoolean()
25
+ @IsOptional()
26
+ @TransformBoolean()
27
+ public readonly whitelist?: boolean;
28
+
29
+ /**
30
+ * If set to true, instead of stripping non-whitelisted properties,
31
+ * validator will throw an error.
32
+ * @default true
33
+ */
34
+ @IsBoolean()
35
+ @IsOptional()
36
+ @TransformBoolean()
37
+ public readonly forbidNonWhitelisted?: boolean;
38
+
39
+ /**
40
+ * If set to true, class-transformer will attempt transformation based on TS reflected type.
41
+ * @default true
42
+ */
43
+ @IsBoolean()
44
+ @IsOptional()
45
+ @TransformBoolean()
46
+ public readonly transform?: boolean;
47
+ }
@@ -0,0 +1,23 @@
1
+ server:
2
+ port: 3001
3
+
4
+ cors:
5
+ enabled: false
6
+
7
+ helmet:
8
+ enabled: false
9
+
10
+ swagger:
11
+ enabled: false
12
+
13
+ db:
14
+ connectionString: ${DATABASE_URL:-postgresql://postgres:postgres@localhost:5432/dismissible}
15
+
16
+ jwtAuth:
17
+ enabled: false
18
+
19
+ validation:
20
+ disableErrorMessages: false
21
+ whitelist: true
22
+ forbidNonWhitelisted: true
23
+ transform: true
@@ -0,0 +1,26 @@
1
+ server:
2
+ port: 3001
3
+
4
+ cors:
5
+ enabled: false
6
+
7
+ helmet:
8
+ enabled: false
9
+
10
+ swagger:
11
+ enabled: false
12
+
13
+ db:
14
+ connectionString: ${DATABASE_URL:-postgresql://postgres:postgres@localhost:5432/dismissible}
15
+
16
+ jwtAuth:
17
+ enabled: true
18
+ wellKnownUrl: https://auth.example.com/.well-known/openid-configuration
19
+ issuer: https://auth.example.com
20
+ audience: dismissible-api
21
+
22
+ validation:
23
+ disableErrorMessages: false
24
+ whitelist: true
25
+ forbidNonWhitelisted: true
26
+ transform: true
@@ -0,0 +1,61 @@
1
+ import { INestApplication } from '@nestjs/common';
2
+ import request from 'supertest';
3
+ import { join } from 'path';
4
+ import { createTestApp, cleanupTestData } from '../src/app-test.factory';
5
+ import { NullLogger } from '@dismissible/nestjs-logger';
6
+
7
+ describe('DELETE /v1/users/:userId/items/:id (dismiss)', () => {
8
+ let app: INestApplication;
9
+
10
+ beforeAll(async () => {
11
+ app = await createTestApp({
12
+ moduleOptions: {
13
+ configPath: join(__dirname, 'config'),
14
+ logger: NullLogger,
15
+ },
16
+ });
17
+ await cleanupTestData(app);
18
+ });
19
+
20
+ afterAll(async () => {
21
+ await cleanupTestData(app);
22
+ await app.close();
23
+ });
24
+
25
+ it('should dismiss an existing item', async () => {
26
+ const userId = 'user-dismiss-1';
27
+ await request(app.getHttpServer()).get(`/v1/users/${userId}/items/dismiss-test-1`).expect(200);
28
+
29
+ const response = await request(app.getHttpServer())
30
+ .delete(`/v1/users/${userId}/items/dismiss-test-1`)
31
+ .expect(200);
32
+
33
+ expect(response.body.data).toBeDefined();
34
+ expect(response.body.data.dismissedAt).toBeDefined();
35
+ });
36
+
37
+ it('should return 400 when dismissing non-existent item', async () => {
38
+ const response = await request(app.getHttpServer())
39
+ .delete('/v1/users/user-123/items/non-existent-item')
40
+ .expect(400);
41
+
42
+ expect(response.body.error).toBeDefined();
43
+ expect(response.body.error.message).toContain('not found');
44
+ });
45
+
46
+ it('should return 400 when dismissing already dismissed item', async () => {
47
+ const userId = 'user-dismiss-2';
48
+ await request(app.getHttpServer()).get(`/v1/users/${userId}/items/dismiss-test-2`).expect(200);
49
+
50
+ await request(app.getHttpServer())
51
+ .delete(`/v1/users/${userId}/items/dismiss-test-2`)
52
+ .expect(200);
53
+
54
+ const response = await request(app.getHttpServer())
55
+ .delete(`/v1/users/${userId}/items/dismiss-test-2`)
56
+ .expect(400);
57
+
58
+ expect(response.body.error).toBeDefined();
59
+ expect(response.body.error.message).toContain('already dismissed');
60
+ });
61
+ });
@@ -0,0 +1,55 @@
1
+ import { INestApplication } from '@nestjs/common';
2
+ import request from 'supertest';
3
+ import { join } from 'path';
4
+ import { createTestApp, cleanupTestData } from '../src/app-test.factory';
5
+ import { NullLogger } from '@dismissible/nestjs-logger';
6
+
7
+ describe('Full lifecycle flow', () => {
8
+ let app: INestApplication;
9
+
10
+ beforeAll(async () => {
11
+ app = await createTestApp({
12
+ moduleOptions: {
13
+ configPath: join(__dirname, 'config'),
14
+ logger: NullLogger,
15
+ },
16
+ });
17
+ await cleanupTestData(app);
18
+ });
19
+
20
+ afterAll(async () => {
21
+ if (app) {
22
+ await cleanupTestData(app);
23
+ await app.close();
24
+ }
25
+ });
26
+
27
+ it('should handle create -> dismiss -> restore -> dismiss cycle', async () => {
28
+ const userId = 'lifecycle-user';
29
+ const itemId = 'lifecycle-test';
30
+
31
+ const createResponse = await request(app.getHttpServer())
32
+ .get(`/v1/users/${userId}/items/${itemId}`)
33
+ .expect(200);
34
+
35
+ expect(createResponse.body.data.dismissedAt).toBeUndefined();
36
+
37
+ const dismissResponse = await request(app.getHttpServer())
38
+ .delete(`/v1/users/${userId}/items/${itemId}`)
39
+ .expect(200);
40
+
41
+ expect(dismissResponse.body.data.dismissedAt).toBeDefined();
42
+
43
+ const restoreResponse = await request(app.getHttpServer())
44
+ .post(`/v1/users/${userId}/items/${itemId}`)
45
+ .expect(201);
46
+
47
+ expect(restoreResponse.body.data.dismissedAt).toBeUndefined();
48
+
49
+ const dismissAgainResponse = await request(app.getHttpServer())
50
+ .delete(`/v1/users/${userId}/items/${itemId}`)
51
+ .expect(200);
52
+
53
+ expect(dismissAgainResponse.body.data.dismissedAt).toBeDefined();
54
+ });
55
+ });
@@ -0,0 +1,51 @@
1
+ import { INestApplication } from '@nestjs/common';
2
+ import request from 'supertest';
3
+ import { join } from 'path';
4
+ import { createTestApp, cleanupTestData } from '../src/app-test.factory';
5
+ import { NullLogger } from '@dismissible/nestjs-logger';
6
+
7
+ describe('GET /v1/users/:userId/items/:id (get-or-create)', () => {
8
+ let app: INestApplication;
9
+
10
+ beforeAll(async () => {
11
+ app = await createTestApp({
12
+ moduleOptions: {
13
+ configPath: join(__dirname, 'config'),
14
+ logger: NullLogger,
15
+ },
16
+ });
17
+ await cleanupTestData(app);
18
+ });
19
+
20
+ afterAll(async () => {
21
+ await cleanupTestData(app);
22
+ await app.close();
23
+ });
24
+
25
+ it('should create a new item on first request', async () => {
26
+ const response = await request(app.getHttpServer())
27
+ .get('/v1/users/user-123/items/test-banner-1')
28
+ .expect(200);
29
+
30
+ expect(response.body.data).toBeDefined();
31
+ expect(response.body.data.itemId).toBe('test-banner-1');
32
+ expect(response.body.data.userId).toBe('user-123');
33
+ expect(response.body.data.createdAt).toBeDefined();
34
+ expect(response.body.data.dismissedAt).toBeUndefined();
35
+ });
36
+
37
+ it('should return existing item on subsequent requests', async () => {
38
+ const firstResponse = await request(app.getHttpServer())
39
+ .get('/v1/users/user-456/items/test-banner-2')
40
+ .expect(200);
41
+
42
+ const createdAt = firstResponse.body.data.createdAt;
43
+
44
+ const secondResponse = await request(app.getHttpServer())
45
+ .get('/v1/users/user-456/items/test-banner-2')
46
+ .expect(200);
47
+
48
+ expect(secondResponse.body.data.itemId).toBe('test-banner-2');
49
+ expect(secondResponse.body.data.createdAt).toBe(createdAt);
50
+ });
51
+ });