ai-bot/app/_lib/data/link.ts

107 lines
2.6 KiB
TypeScript

"use server";
import { getCollection } from "../mongodb";
export type Link = {
name: string;
link?: string;
description: string;
_id: string;
type: string;
priority: number;
articleId?: string;
logoLink: string;
isHot?: boolean;
addTime: number;
}
export async function getLinkListAll() {
const linkCollection = await getCollection('link');
const list = await linkCollection.aggregate<Link>([
{
'$addFields': {
'cleanedLink': {
'$substrBytes': [
{
'$arrayElemAt': [
{
'$split': [
'$link', '?'
]
}, 0
]
}, 0, 1000
]
}
}
}, {
'$lookup': {
'from': 'article',
'localField': 'link',
'foreignField': 'link',
'as': 'article'
}
}, {
'$addFields': {
'articleId': {
'$toString':
{
'$arrayElemAt': [
'$article._id', 0
]
}
},
'_id': {
'$toString': "$_id"
}
}
}, {
'$project': {
'article': 0
}
}
]).toArray();
return list;
}
// Link 类型定义
export async function getLinkList({ page = 1, pageSize = 9999, typeId }: {
page?: number;
pageSize?: number;
typeId?: string;
}) {
const collection = await getCollection('link');
const startIndex = (page - 1) * pageSize;
// 构建查询条件对象
const query = {
type: typeId
} as any;
if (!typeId) {
// 如果 typeId 不存在,将其删除
delete query.type
}
const pipeline = [
// 根据构建好的查询条件筛选文档
{ $match: query },
{ $sort: { priority: 1 } },
{ $skip: startIndex },
{ $limit: pageSize },
{
$addFields: {
_id: { $toString: "$_id" }
}
}
];
const cursor = collection.aggregate<Link>(pipeline);
const list = await cursor.toArray();
// 获取符合查询条件的文档总数
const total = await collection.countDocuments(query);
return {
total,
list
}
}