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: Add body validation #49

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions src/controllers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,23 @@ import {
AuthenticatedRequest,
LoginParams,
} from 'types';
import { validateLoginSchema, validateUserSchema } from 'data-schemas/auth';

@Route('v1/auth')
export class AuthControllerV1 extends Controller {
@Post('/register')
public async register(@Body() user: CreateUserParams): Promise<ReturnAuth> {
validateUserSchema(user);

const authReturn = await AuthService.register(user);
this.setStatus(httpStatus.CREATED);
return authReturn;
}

@Post('/login')
public async login(@Body() loginParams: LoginParams): Promise<ReturnAuth> {
validateLoginSchema(loginParams);

const authReturn = await AuthService.login(loginParams);
this.setStatus(httpStatus.OK);
return authReturn;
Expand Down
45 changes: 45 additions & 0 deletions src/data-schemas/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { ZodError, z } from 'zod';

import { CreateUserParams, LoginParams } from 'types';
import { ApiError } from 'utils/apiError';
import { errors } from 'config/errors';
import { formatZodError } from 'utils/validator';

const MINIMUM_PASSWORD_LENGTH = 10;

const userCreationSchema = z.object({
email: z.string().email({ message: 'Invalid email' }),
name: z.string(),
password: z
.string()
.min(MINIMUM_PASSWORD_LENGTH, { message: "Can't be an empty password" }),
});

export type UserCreationSchema = z.infer<typeof userCreationSchema>;

const loginSchema = z.object({
email: z.string().email({ message: 'Invalid email' }),
password: z
.string()
.min(MINIMUM_PASSWORD_LENGTH, { message: "Can't be an empty password" }),
});

export type UserLoginSchema = z.infer<typeof loginSchema>;

export const validateUserSchema = (user: CreateUserParams) => {
try {
userCreationSchema.parse(user);
} catch (err) {
const formattedZodError = formatZodError(err as ZodError);
throw new ApiError(errors.VALIDATION_ERROR, true, formattedZodError);
}
};

export const validateLoginSchema = (loginParams: LoginParams) => {
try {
loginSchema.parse(loginParams);
} catch (err) {
const formattedZodError = formatZodError(err as ZodError);
throw new ApiError(errors.VALIDATION_ERROR, true, formattedZodError);
}
};
8 changes: 7 additions & 1 deletion src/middlewares/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ export const errorConverter = (
next(error);
};

export const errorHandler = (err: ApiError, req: Request, res: Response) => {
export const errorHandler = (
err: ApiError,
req: Request,
res: Response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
next: NextFunction,
) => {
let { httpCode, message } = err;
if (!err.isOperational) {
httpCode =
Expand Down
11 changes: 11 additions & 0 deletions src/utils/validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { ZodError } from 'zod';

export const formatZodError = (zodError: ZodError) => {
const formattedError = zodError.errors.map((error) => {
return {
field: error.path,
error: error.message,
};
});
return formattedError;
};
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"tests/*": ["tests/*"],
"types/*": ["types/*"],
"utils/*": ["utils/*"],
"data-schemas/*": ["data-schemas/*"],
"root/*": ["../*"]
}
}
Expand Down
1 change: 1 addition & 0 deletions tsoa.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"tests/*": ["tests/*"],
"types/*": ["types/*"],
"utils/*": ["utils/*"],
"data-schemas/*": ["data-schemas/*"],
"root/*": ["../*"]
}
}
Expand Down