// app/api/cron/forms/start/route.ts import { NextRequest } from 'next/server'; import { v4 as uuidv4 } from 'uuid'; import { revalidateTag } from 'next/cache'; // 동기화 작업의 상태를 저장할 Map // 실제 프로덕션에서는 Redis 또는 DB에 저장하는 것이 좋습니다 const syncJobs = new Map(); export async function POST(request: NextRequest) { try { // 고유 ID 생성 const syncId = uuidv4(); // 작업 상태 초기화 syncJobs.set(syncId, { status: 'queued', startTime: new Date(), }); // 비동기 작업 시작 (백그라운드에서 실행) processSyncJob(syncId).catch(error => { console.error('Background sync job failed:', error); syncJobs.set(syncId, { ...syncJobs.get(syncId)!, status: 'failed', endTime: new Date(), error: error.message || 'Unknown error occurred' }); }); // 즉시 응답 반환 (작업 ID 포함) return Response.json({ success: true, message: 'Form sync job started', syncId }, { status: 200 }); } catch (error: any) { console.error('Failed to start sync job:', error); return Response.json({ success: false, error: error.message || 'Failed to start sync job' }, { status: 500 }); } } // 백그라운드에서 실행되는 동기화 작업 async function processSyncJob(syncId: string) { try { // 상태 업데이트: 처리 중 syncJobs.set(syncId, { ...syncJobs.get(syncId)!, status: 'processing', progress: 0, }); // 여기서 실제 동기화 로직 가져오기 const { syncTagFormMappings } = await import('@/lib/sedp/sync-form'); // 실제 동기화 작업 실행 const result = await syncTagFormMappings(); // 명시적으로 캐시 무효화 (동적 import 대신 상단에서 import) revalidateTag('form-lists'); // 상태 업데이트: 완료 syncJobs.set(syncId, { ...syncJobs.get(syncId)!, status: 'completed', endTime: new Date(), result, progress: 100, }); return result; } catch (error: any) { // 에러 발생 시 상태 업데이트 syncJobs.set(syncId, { ...syncJobs.get(syncId)!, status: 'failed', endTime: new Date(), error: error.message || 'Unknown error occurred', }); throw error; // 에러 다시 던지기 } } // 서버 메모리에 저장된 작업 상태 접근 함수 (다른 API에서 사용) export function getSyncJobStatus(id: string) { return syncJobs.get(id); }