feat(server): introduce user friendly server errors (#7111)
This commit is contained in:
@@ -1,36 +1,23 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import z from 'zod';
|
||||
|
||||
function assertValid<T>(z: z.ZodType<T>, value: unknown) {
|
||||
const result = z.safeParse(value);
|
||||
|
||||
if (!result.success) {
|
||||
const firstIssue = result.error.issues.at(0);
|
||||
if (firstIssue) {
|
||||
throw new BadRequestException(firstIssue.message);
|
||||
} else {
|
||||
throw new BadRequestException('Invalid credential');
|
||||
}
|
||||
}
|
||||
}
|
||||
import { InvalidEmail, InvalidPasswordLength } from '../../fundamentals';
|
||||
|
||||
export function assertValidEmail(email: string) {
|
||||
assertValid(z.string().email({ message: 'Invalid email address' }), email);
|
||||
const result = z.string().email().safeParse(email);
|
||||
if (!result.success) {
|
||||
throw new InvalidEmail();
|
||||
}
|
||||
}
|
||||
|
||||
export function assertValidPassword(
|
||||
password: string,
|
||||
{ min, max }: { min: number; max: number }
|
||||
) {
|
||||
assertValid(
|
||||
z
|
||||
.string()
|
||||
.min(min, { message: `Password must be ${min} or more charactors long` })
|
||||
.max(max, {
|
||||
message: `Password must be ${max} or fewer charactors long`,
|
||||
}),
|
||||
password
|
||||
);
|
||||
const result = z.string().min(min).max(max).safeParse(password);
|
||||
|
||||
if (!result.success) {
|
||||
throw new InvalidPasswordLength({ min, max });
|
||||
}
|
||||
}
|
||||
|
||||
export const validators = {
|
||||
|
||||
Reference in New Issue
Block a user