summaryrefslogtreecommitdiff
path: root/app/api/cron/forms/route.ts
blob: abe6753a69fc91d26ca50ab973e334bdade01a96 (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
// 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<Promise<any>>;
}

// 글로벌 태스크 집합 초기화 (서버가 시작될 때만 한 번 실행됨)
if (!global.pendingTasks) {
  global.pendingTasks = new Set<Promise<any>>();
}

// 이 함수는 비동기 작업을 더 안전하게 처리하기 위한 도우미 함수입니다
function runBackgroundTask<T>(task: Promise<T>, taskName: string): Promise<T> {
  // 작업을 추적 세트에 추가
  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 });
  }
}