ai-bot/app/api/link/route.ts

67 lines
2.1 KiB
TypeScript

import { verifySession } from "@/app/_lib/dal";
import { User } from "@/app/_lib/data/user";
import { getCollection, getDb } from "@/app/_lib/mongodb";
import { message } from "antd";
import bcrypt from 'bcrypt';
import { ObjectId } from "mongodb";
import { NextRequest } from "next/server";
export type Link = {
name: string;
link?: string;
description: string;
_id: string;
type: string;
priority: number;
logoLink: string;
isHot?: boolean;
}
export async function GET(req: NextRequest) {
try {
const collection = await getCollection('link');
// Check if the user is authenticated
const page = parseInt(req.nextUrl.searchParams.get('page') || '1') || 1;
const pageSize = parseInt(req.nextUrl.searchParams.get('pageSize') || '10') || 10;
const typeId = req.nextUrl.searchParams.get('typeId')
// 计算起始索引和结束索引
const startIndex = (page - 1) * pageSize;
// 查询数据
const cursor = collection.find<Link>({ type: typeId }).skip(startIndex).limit(pageSize);
const data = await cursor.toArray();
// 计算总数量
const total = (await collection.find<Link>({ type: typeId }).toArray()).length
return Response.json({
total,
list: data,
})
} catch (e) {
return Response.error()
}
}
export async function POST(req: NextRequest) {
try {
// 获取待插入的对象
const link = await req.json()
const collection = await getCollection('link')
await collection.insertOne(link)
return Response.json({ message: '成功' })
} catch (e) {
return Response.error()
}
}
export async function PUT(req: NextRequest) {
try {
// 获取待更新的对象
const link = await req.json() as Link
const collection = await getCollection('link')
await collection.replaceOne({ _id: new ObjectId(link._id) }, { ...link, _id: new ObjectId(link._id) })
return Response.json({ message: '成功' })
} catch (e) {
return Response.error()
}
}