// app/api/cron/forms/route.ts import { syncTagFormMappings } from '@/lib/sedp/sync-form'; import { NextRequest } from 'next/server'; import { revalidateTag } from 'next/cache'; // TypeScript에서 global 객체를 확장하기 위한 type 선언 declare global { var pendingTasks: Set>; } // 글로벌 태스크 집합 초기화 (서버가 시작될 때만 한 번 실행됨) if (!global.pendingTasks) { global.pendingTasks = new Set>(); } // 이 함수는 비동기 작업을 더 안전하게 처리하기 위한 도우미 함수입니다 function runBackgroundTask(task: Promise, taskName: string): Promise { // 작업을 추적 세트에 추가 global.pendingTasks.add(task); // finally 블록을 사용하여 작업이 완료될 때 세트에서 제거 task .then(result => { console.log(`Background task '${taskName}' completed successfully`); return result; }) .catch(error => { console.error(`Background task '${taskName}' failed:`, error); }) .finally(() => { global.pendingTasks.delete(task); }); return task; } export async function GET(request: NextRequest) { try { console.log('태그 폼 매핑 동기화 API 호출됨:', new Date().toISOString()); // 비동기 작업을 생성하고 전역 객체에 저장 const syncTask = syncTagFormMappings() .then(result => { // 작업이 완료되면 캐시 무효화 revalidateTag('form-lists'); return result; }); // 백그라운드에서 작업이 계속 실행되도록 보장 runBackgroundTask(syncTask, 'form-sync'); // 먼저 상태를 반환하고, 그 동안 백그라운드에서 작업 계속 return new Response( JSON.stringify({ success: true, message: 'Form sync started in background. This may take a while.' }), { status: 202, headers: { 'Content-Type': 'application/json' } } ); } catch (error: any) { console.error('태그 폼 매핑 동기화 API 에러:', error); const message = error.message || 'Something went wrong'; return Response.json({ success: false, error: message }, { status: 500 }); } }