Files
code-center/src/routes-simple/router.ts
abearxiong 158dd9e85c Refactor AI proxy error handling and remove deprecated upload and event routes
- Updated `getAiProxy` function to return a JSON response for missing objects when the user is the owner.
- Removed the `upload.ts`, `event.ts`, and related middleware files to streamline the codebase.
- Cleaned up `handle-request.ts` and `index.ts` by removing unused imports and routes.
- Deleted chunk upload handling and related utility functions to simplify resource management.
- Enhanced app manager list functionality to support app creation if not found.
2026-02-02 18:06:31 +08:00

81 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { router } from '@/app.ts';
import http from 'http';
import { useContextKey } from '@kevisual/context';
export { router, };
/**
* 事件客户端
*/
const eventClientsInit = () => {
const clients = new Map<string, { client?: http.ServerResponse; createTime?: number;[key: string]: any }>();
return clients;
};
export const clients = useContextKey('event-clients', () => eventClientsInit());
/**
* 获取 task-id
* @param req
* @returns
*/
export const getTaskId = (req: http.IncomingMessage) => {
const url = new URL(req.url || '', 'http://localhost');
const taskId = url.searchParams.get('taskId');
if (taskId) {
return taskId;
}
return req.headers['task-id'] as string;
};
type EventData = {
progress: number | string;
message: string;
};
/**
* 写入事件
* @param req
* @param data
*/
export const writeEvents = (req: http.IncomingMessage, data: EventData) => {
const taskId = getTaskId(req);
if (taskId) {
const client = clients.get(taskId)?.client;
if (client) {
client.write(`data: ${JSON.stringify(data)}\n\n`);
}
if (Number(data.progress) === 100) {
clients.delete(taskId);
}
} else {
console.log('taskId is remove.', taskId);
}
};
/**
* 查找超出2个小时的clients都删除了
*/
export const deleteOldClients = () => {
const now = Date.now();
for (const [taskId, client] of clients) {
// 如果创建时间超过2个小时则删除
if (now - client.createTime > 1000 * 60 * 60 * 2) {
clients.delete(taskId);
}
}
};
/**
* 解析表单数据, 如果表单数据是数组, 则取第一个appKey, version, username 等
* @param fields 表单数据
* @param parseKeys 需要解析的键
* @returns 解析后的数据
*/
export const getKey = (fields: Record<string, any>, parseKeys: string[]) => {
let value: Record<string, any> = {};
for (const key of parseKeys) {
const v = fields[key];
if (Array.isArray(v)) {
value[key] = v[0];
} else {
value[key] = v;
}
}
return value;
};