refactor: 提取 validation.ts 和 amap.ts,统一 API 路由校验逻辑

新增 validation.ts(用户名/密码/邮箱/内容/房间名/必填字段校验)
和 amap.ts(AMAP API key 校验),消除 7 个路由中的重复验证代码。
This commit is contained in:
2026-02-26 19:22:17 +08:00
parent 455b9e04d8
commit 1229bb849b
9 changed files with 80 additions and 41 deletions
+7
View File
@@ -0,0 +1,7 @@
import { ApiError } from "@/lib/api";
export function requireAmapApiKey(): string {
const key = process.env.AMAP_API_KEY;
if (!key) throw new ApiError("服务配置异常,请稍后重试", 500);
return key;
}
+47
View File
@@ -0,0 +1,47 @@
import { ApiError } from "@/lib/api";
export function validateUsername(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length < 2 || trimmed.length > 16) {
throw new ApiError("用户名需要 2-16 个字符");
}
return trimmed;
}
export function validatePassword(password: string, label = "密码"): void {
if (password.length < 6) {
throw new ApiError(`${label}至少 6 个字符`);
}
}
export function validateEmail(email: string): void {
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
throw new ApiError("邮箱格式不正确");
}
}
export function validateIdeaContent(raw: unknown): string {
if (!raw || typeof raw !== "string" || raw.trim().length === 0) {
throw new ApiError("内容不能为空");
}
const trimmed = raw.trim();
if (trimmed.length > 200) {
throw new ApiError("内容不能超过 200 字");
}
return trimmed;
}
export function validateRoomName(raw: unknown, fallback = "我们的周末"): string {
const trimmed = ((raw as string) || "").trim() || fallback;
if (trimmed.length > 30) {
throw new ApiError("房间名不能超过 30 个字");
}
return trimmed;
}
export function requireString(value: unknown, fieldName: string): string {
if (!value || typeof value !== "string") {
throw new ApiError(`${fieldName}不能为空`);
}
return value;
}