summaryrefslogtreecommitdiff
path: root/app/api/cron/forms/start/route.ts
blob: a99c467767101a9b34f28c6ad52a3c57c066ff10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// 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<string, {
  status: 'queued' | 'processing' | 'completed' | 'failed';
  startTime: Date;
  endTime?: Date;
  result?: any;
  error?: string;
  progress?: number;
}>();

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);
}