Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/swagger UI v2 #32

Merged
merged 9 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
["^"], // <-- to match regular imports (not starting with a special character)

// Your internal path aliases
["^(@modules|@common|@src)(/.*|$)"],
["^(@modules|@common|@src|@api-docs)(/.*|$)"],

// Relative imports
["^\\.\\.(?!/?$)", "^\\.\\./?$"],
Expand Down
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
build
coverage
.eslintcache
.eslintcache
tsconfig.json
10 changes: 9 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,13 @@
"tabWidth": 2,
"printWidth": 120,
"singleQuote": true,
"semi": true
"semi": true,
"overrides": [
{
"files": "*.json",
"options": {
"parser": "json"
}
}
]
}
1 change: 0 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ module.exports = {
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
prefix: '<rootDir>/',
}),

transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
Expand Down
5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,7 @@
"typescript": "^5.3.3"
},
"lint-staged": {
"**/*.{ts,js,json}": [
"npm run lint",
"npm run format"
],
"**/*.{ts,js,json}": ["npm run lint", "npm run format"],
"src/**/*.{ts,js,json}": "npm run format",
"tests/**/*.{ts,js,json}": "npm run format"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { OpenApiGeneratorV3, OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';

import { healthCheckRegistry } from '@modules/healthCheck/healthCheckRegistry';
import { userRegistry } from '@modules/user/userRegistry';
import { healthCheckRegistry } from '@modules/healthCheck/healthCheckRouter';
import { userRegistry } from '@modules/user/userRouter';

export function generateOpenAPIDocument() {
const registry = new OpenAPIRegistry([healthCheckRegistry, userRegistry]);
Expand Down
41 changes: 41 additions & 0 deletions src/api-docs/openAPIResponseBuilders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { StatusCodes } from 'http-status-codes';
import { z } from 'zod';

import { ServiceResponseSchema } from '@common/models/serviceResponse';

export function createApiResponse(schema: z.ZodTypeAny, description: string, statusCode = StatusCodes.OK) {
return {
[statusCode]: {
description,
content: {
'application/json': {
schema: ServiceResponseSchema(schema),
},
},
},
};
}

// Use if you want multiple responses for a single endpoint

// import { ResponseConfig } from '@asteasolutions/zod-to-openapi';
// import { ApiResponseConfig } from '@common/models/openAPIResponseConfig';
// export type ApiResponseConfig = {
// schema: z.ZodTypeAny;
// description: string;
// statusCode: StatusCodes;
// };
// export function createApiResponses(configs: ApiResponseConfig[]) {
// const responses: { [key: string]: ResponseConfig } = {};
// configs.forEach(({ schema, description, statusCode }) => {
// responses[statusCode] = {
// description,
// content: {
// 'application/json': {
// schema: ServiceResponseSchema(schema),
// },
// },
// };
// });
// return responses;
// }
30 changes: 0 additions & 30 deletions src/modules/healthCheck/healthCheckRegistry.ts

This file was deleted.

12 changes: 12 additions & 0 deletions src/modules/healthCheck/healthCheckRouter.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
import { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
import express, { Request, Response, Router } from 'express';
import { StatusCodes } from 'http-status-codes';
import { z } from 'zod';

import { createApiResponse } from '@api-docs/openAPIResponseBuilders';
import { ResponseStatus, ServiceResponse } from '@common/models/serviceResponse';
import { handleServiceResponse } from '@common/utils/httpHandlers';

export const healthCheckRegistry = new OpenAPIRegistry();

export const healthCheckRouter: Router = (() => {
const router = express.Router();

healthCheckRegistry.registerPath({
method: 'get',
path: '/health-check',
tags: ['Health Check'],
responses: createApiResponse(z.null(), 'Success'),
});

router.get('/', (_req: Request, res: Response) => {
const serviceResponse = new ServiceResponse(ResponseStatus.Success, 'Service is healthy', null, StatusCodes.OK);
handleServiceResponse(serviceResponse, res);
Expand Down
26 changes: 11 additions & 15 deletions src/modules/user/userModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,16 @@ import { commonValidations } from '@common/utils/commonValidation';
extendZodWithOpenApi(z);

export type User = z.infer<typeof UserSchema>;
export const UserSchema = z
.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
age: z.number(),
createdAt: z.date(),
updatedAt: z.date(),
})
.openapi('User');
export const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
age: z.number(),
createdAt: z.date(),
updatedAt: z.date(),
});

// Schema for 'GET users/:id' endpoint
export const GetUserSchema = z
.object({
params: z.object({ id: commonValidations.id }),
})
.openapi('GetUser');
export const GetUserSchema = z.object({
params: z.object({ id: commonValidations.id }),
});
69 changes: 0 additions & 69 deletions src/modules/user/userRegistry.ts

This file was deleted.

25 changes: 24 additions & 1 deletion src/modules/user/userRouter.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,41 @@
import { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
import express, { Request, Response, Router } from 'express';
import { z } from 'zod';

import { createApiResponse } from '@api-docs/openAPIResponseBuilders';
import { handleServiceResponse, validateRequest } from '@common/utils/httpHandlers';
import { userService } from '@modules/user/userService';

import { GetUserSchema } from './userModel';
import { GetUserSchema, UserSchema } from './userModel';

export const userRegistry = new OpenAPIRegistry();

userRegistry.register('User', UserSchema);
userRegistry.register('GetUser', GetUserSchema);

export const userRouter: Router = (() => {
const router = express.Router();

userRegistry.registerPath({
method: 'get',
path: '/users',
tags: ['User'],
responses: createApiResponse(z.array(UserSchema), 'Success'),
});

router.get('/', async (_req: Request, res: Response) => {
const serviceResponse = await userService.findAll();
handleServiceResponse(serviceResponse, res);
});

userRegistry.registerPath({
method: 'get',
path: '/users/{id}',
tags: ['User'],
request: { params: GetUserSchema.shape.params },
responses: createApiResponse(UserSchema, 'Success'),
});

router.get('/:id', validateRequest(GetUserSchema), async (req: Request, res: Response) => {
const id = parseInt(req.params.id as string, 10);
const serviceResponse = await userService.findById(id);
Expand Down
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import path from 'path';
import { pino } from 'pino';
import swaggerUi from 'swagger-ui-express';

import { generateOpenAPIDocument } from '@api-docs/openAPIDocumentGenerator';
import errorHandler from '@common/middleware/errorHandler';
import { generateOpenAPIDocument } from '@common/middleware/openAPIDocument';
import rateLimiter from '@common/middleware/rateLimiter';
import requestLogger from '@common/middleware/requestLogger';
import { getCorsOrigin } from '@common/utils/envConfig';
Expand Down
7 changes: 4 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
"module": "CommonJS",
"baseUrl": ".",
"paths": {
"@modules/*": ["./src/modules/*"],
"@common/*": ["./src/common/*"],
"@src/*": ["./src/*"]
"@api-docs/*": ["src/api-docs/*"],
"@common/*": ["src/common/*"],
"@modules/*": ["src/modules/*"],
"@src/*": ["src/*"]
},
"moduleResolution": "Node",
"outDir": "build",
Expand Down