feat: 上传资源和下载资源更新
This commit is contained in:
@@ -9,7 +9,7 @@ export { router, checkAuth, error };
|
||||
* 事件客户端
|
||||
*/
|
||||
const eventClientsInit = () => {
|
||||
const clients = new Map<string, { client?: http.ServerResponse; [key: string]: any }>();
|
||||
const clients = new Map<string, { client?: http.ServerResponse; createTime?: number; [key: string]: any }>();
|
||||
return clients;
|
||||
};
|
||||
export const clients = useContextKey('event-clients', () => eventClientsInit());
|
||||
@@ -19,18 +19,49 @@ export const clients = useContextKey('event-clients', () => eventClientsInit());
|
||||
* @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: any) => {
|
||||
export const writeEvents = (req: http.IncomingMessage, data: EventData) => {
|
||||
const taskId = getTaskId(req);
|
||||
taskId && clients.get(taskId)?.client?.write?.(`${JSON.stringify(data)}\n`);
|
||||
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 表单数据
|
||||
|
||||
Reference in New Issue
Block a user