feat(server): introduce user friendly server errors (#7111)

This commit is contained in:
liuyi
2024-06-17 11:30:58 +08:00
committed by GitHub
parent 5307a55f8a
commit 54fc1197ad
65 changed files with 3170 additions and 924 deletions

View File

@@ -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 = {