feat: Enhance registration process with improved validation and error handling

This commit is contained in:
beilunyang
2025-01-15 18:52:11 +08:00
parent 126a4cb948
commit 075a34239b
3 changed files with 24 additions and 14 deletions

View File

@@ -1,25 +1,28 @@
import { NextResponse } from "next/server"
import { register } from "@/lib/auth"
import { authSchema } from "@/lib/validation"
import { ZodError } from "zod"
import { authSchema, AuthSchema } from "@/lib/validation"
export const runtime = "edge"
export async function POST(request: Request) {
try {
const json = await request.json()
const body = authSchema.parse(json)
await register(body.username, body.password)
return Response.json({ success: true })
} catch (error) {
if (error instanceof ZodError) {
return Response.json(
{ error: error.errors[0].message },
const json = await request.json() as AuthSchema
try {
authSchema.parse(json)
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "输入格式不正确" },
{ status: 400 }
)
}
return Response.json(
const { username, password } = json
const user = await register(username, password)
return NextResponse.json({ user })
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "注册失败" },
{ status: 500 }
)