expo-popcore-old/lib/api/template-runs.ts

93 lines
2.1 KiB
TypeScript

import { postApiTemplatesByIdRun, getApiTemplateGenerationsById } from '@repo/loomart-sdk';
import { loomartClient } from './loomart-client';
import { RunTemplateData } from '../types/template-run';
export const runTemplate = async (
templateId: string,
data: RunTemplateData,
identifier: string
) => {
if (!identifier) {
throw new Error('支付凭证缺失,无法创建生成任务');
}
const result = await postApiTemplatesByIdRun({
client: loomartClient,
path: { id: templateId },
body: { data, identifier },
});
return result.data;
};
export const getTemplateGeneration = async (generationId: string) => {
const { data } = await getApiTemplateGenerationsById({
client: loomartClient,
path: { id: generationId },
});
return data;
};
export function pollTemplateGeneration(
generationId: string,
onComplete: (result: any) => void,
onError: (error: Error) => void,
maxAttempts: number = 100,
intervalMs: number = 3000
): () => void {
let attempts = 0;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let isCancelled = false;
const poll = async () => {
if (isCancelled) return;
try {
attempts++;
if (attempts > maxAttempts) {
throw new Error('轮询超时,请稍后重试');
}
const response = await getTemplateGeneration(generationId);
if (!response) {
throw new Error('请稍后重试');
}
const generation = response.data;
if (isCancelled) return;
// 检查是否完成
if (generation.status === 'completed') {
onComplete(generation);
return;
}
// 检查是否失败
if (generation.status === 'failed') {
throw new Error('任务执行失败');
}
// 继续轮询
if (!isCancelled) {
timeoutId = setTimeout(poll, intervalMs);
}
} catch (error) {
if (!isCancelled) {
onError(error as Error);
}
}
};
// 开始轮询
timeoutId = setTimeout(poll, intervalMs);
// 返回取消函数
return () => {
isCancelled = true;
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
}