/**
* 获取项目列表工具
*/
import { ZenTaoClient } from '../client';
import { IProject, IProjectQueryParams } from '../types';
import { LRUCache } from '../utils/cache';
export async function getProjectsHandler(
client: ZenTaoClient,
cache: LRUCache<string, any>,
params: IProjectQueryParams
): Promise<any> {
try {
// 生成缓存键
const cacheKey = `projects:${JSON.stringify(params || {})}`;
// 尝试从缓存获取
const cached = cache.get(cacheKey);
if (cached) {
return {
content: [
{
type: 'text',
text: `从缓存获取的项目列表(共 ${cached.projects.length} 个):\n\n${cached.projects.map((p: IProject) =>
`• [${p.id}] ${p.name} (${p.code}) - 状态: ${p.status}`
).join('\n')}`,
},
],
structuredContent: cached
};
}
// 构建查询参数
const queryParams: any = {
page: params?.page || 1,
limit: params?.limit || 50,
};
if (params?.status) {
queryParams.status = params.status;
}
if (params?.orderBy) {
queryParams.orderBy = params.orderBy;
}
// 调用 API
const projects = await client.get<IProject[]>('/api.php/v1/projects', queryParams);
// 格式化结构化数据
const structuredData = {
projects: projects,
total: projects.length,
page: params.page || 1,
limit: params.limit || 50
};
// 缓存结果 (10分钟 TTL)
cache.set(cacheKey, structuredData, 10 * 60 * 1000);
// 格式化文本输出
const output = `获取到 ${projects.length} 个项目:\n\n${projects.map((p: IProject) =>
`• [${p.id}] ${p.name} (${p.code}) - 状态: ${p.status}`
).join('\n')}\n\n详细信息:\n${projects.map((p: IProject) =>
`项目 ${p.name}:\n ID: ${p.id}\n 代码: ${p.code}\n 状态: ${p.status}\n 开始: ${p.begin}\n 结束: ${p.end || '未设置'}\n`
).join('\n')}`;
return {
content: [
{
type: 'text',
text: output,
},
],
structuredContent: structuredData
};
} catch (error: any) {
throw new Error(`获取项目列表失败: ${error.message || '未知错误'}`);
}
}