fake_shop/app/api/address/route.js

45 lines
1.2 KiB
JavaScript

import { NextResponse } from "next/server";
import dbConnect from "@/lib/mongodb";
import Address from "@/models/Address";
import { verifyToken } from "@/lib/auth";
export async function GET(request) {
try {
const token = request.headers.get("authorization")?.split(" ")[1];
const decoded = verifyToken(token);
await dbConnect();
const addresses = await Address.find({ userId: decoded.userId });
return NextResponse.json(addresses);
} catch (error) {
return NextResponse.json({ error: "获取地址列表失败" }, { status: 401 });
}
}
export async function POST(request) {
try {
const token = request.headers.get("authorization")?.split(" ")[1];
const decoded = verifyToken(token);
const data = await request.json();
await dbConnect();
// 如果设置为默认地址,需要将其他地址的默认状态取消
if (data.isDefault) {
await Address.updateMany(
{ userId: decoded.userId },
{ isDefault: false }
);
}
const address = await Address.create({
...data,
userId: decoded.userId,
});
return NextResponse.json(address);
} catch (error) {
return NextResponse.json({ error: "添加地址失败" }, { status: 500 });
}
}