gluestick/src/schemas.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-05-09 16:26:36 -04:00
import { z } from "zod";
2023-04-26 21:21:28 -04:00
2023-05-09 16:26:36 -04:00
const USERNAME = z
.string()
2023-04-29 16:32:59 -04:00
.min(1, "Username is too short.")
2023-05-09 16:26:36 -04:00
.regex(/^[a-z0-9]+$/, "Username must be lowercase alphanumeric.");
const DISPLAY_NAME = z.string().min(1, "Display name is too short.");
const EMAIL = z.string().email("Not an email.");
const PASSWORD = z
.string()
2023-04-26 21:21:28 -04:00
.min(12, "Password must be at least 12 characters long.");
2023-05-09 16:26:36 -04:00
const AVATAR = z.string().refine(
(val) => {
const parts = val.split(",");
const data = parts.length === 2 ? parts[1] : parts[0];
2023-04-26 22:59:17 -04:00
try {
2023-05-09 16:26:36 -04:00
const buf = Buffer.from(data, "base64");
2023-04-28 12:08:36 -04:00
return buf.length <= 2_000_000;
2023-04-26 22:59:17 -04:00
} catch (e) {
return false;
}
2023-05-09 16:26:36 -04:00
},
{
message: "File is bigger than 2 MB.",
path: ["avatar"]
2023-04-26 22:59:17 -04:00
}
);
2023-04-26 21:21:28 -04:00
2023-05-09 16:26:36 -04:00
export const loginSchema = z.object({
2023-04-26 21:21:28 -04:00
username: USERNAME,
password: PASSWORD
});
2023-05-09 16:26:36 -04:00
export type LoginSchema = z.infer<typeof loginSchema>;
2023-04-26 21:21:28 -04:00
2023-05-09 16:26:36 -04:00
export const registerSchema = z
.object({
2023-04-26 21:21:28 -04:00
username: USERNAME,
2023-04-26 22:59:17 -04:00
displayName: DISPLAY_NAME,
email: EMAIL,
2023-04-26 21:21:28 -04:00
password: PASSWORD,
2023-05-09 16:26:36 -04:00
confirmPassword: PASSWORD,
avatar: AVATAR.optional()
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match.",
path: ["confirmPassword"]
2023-04-26 21:21:28 -04:00
});
2023-05-09 16:26:36 -04:00
export type RegisterSchema = z.infer<typeof registerSchema>;
2023-04-26 22:59:17 -04:00
2023-05-09 16:26:36 -04:00
export const aboutMeSchema = z.object({
2023-04-26 22:59:17 -04:00
username: USERNAME,
displayName: DISPLAY_NAME,
email: EMAIL,
2023-05-09 16:26:36 -04:00
avatar: AVATAR.optional()
2023-04-26 22:59:17 -04:00
});
2023-05-09 16:26:36 -04:00
export type AboutMeSchema = z.infer<typeof aboutMeSchema>;
2023-04-26 22:59:17 -04:00
2023-05-09 16:26:36 -04:00
export const passwordUpdateSchema = z
.object({
2023-04-26 22:59:17 -04:00
password: PASSWORD,
newPassword: PASSWORD,
2023-05-09 16:26:36 -04:00
confirmPassword: PASSWORD
})
.refine((data) => data.newPassword === data.confirmPassword, {
message: "Passwords do not match.",
path: ["confirmPassword"]
2023-04-27 13:47:30 -04:00
});
2023-05-09 16:26:36 -04:00
export type PasswordUpdateSchema = z.infer<typeof passwordUpdateSchema>;