summaryrefslogtreecommitdiff
path: root/app/api/table/items/infinite/route.ts
blob: 486c307632d55c658d8f2f30f98ddba1dcb24149 (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// app/api/table/items/infinite/route.ts
import { NextRequest, NextResponse } from "next/server";
import { getItemsInfinite, type GetItemsInfiniteInput } from "@/lib/items/service";

// URL 파라미터를 GetItemsInfiniteInput으로 변환하는 헬퍼 함수
function parseUrlParamsToInfiniteInput(searchParams: URLSearchParams): GetItemsInfiniteInput {
  // 무한 스크롤 관련 파라미터
  const cursor = searchParams.get("cursor") || undefined;
  const limit = parseInt(searchParams.get("limit") || "50");

  // 기존 searchParamsCache와 동일한 필드들
  const itemCode = searchParams.get("itemCode") || "";
  const itemName = searchParams.get("itemName") || "";
  const description = searchParams.get("description") || "";
  const parentItemCode = searchParams.get("parentItemCode") || "";
  const itemLevel = parseInt(searchParams.get("itemLevel") || "5");
  const deleteFlag = searchParams.get("deleteFlag") || "";
  const unitOfMeasure = searchParams.get("unitOfMeasure") || "";
  const steelType = searchParams.get("steelType") || "";
  const gradeMaterial = searchParams.get("gradeMaterial") || "";
  const changeDate = searchParams.get("changeDate") || "";
  const baseUnitOfMeasure = searchParams.get("baseUnitOfMeasure") || "";

  // 고급 필터링 관련
  const search = searchParams.get("search") || "";
  const joinOperator = searchParams.get("joinOperator") || "and";
  
  // 필터 파라미터 파싱
  let filters: any[] = [];
  const filtersParam = searchParams.get("filters");
  if (filtersParam) {
    try {
      filters = JSON.parse(filtersParam);
    } catch (e) {
      console.warn("Invalid filters parameter:", e);
      filters = [];
    }
  }

  // 정렬 파라미터 파싱
  let sort: Array<{ id: string; desc: boolean }> = [];
  const sortParam = searchParams.get("sort");
  if (sortParam) {
    try {
      sort = JSON.parse(sortParam);
    } catch (e) {
      console.warn("Invalid sort parameter:", e);
      // 기본 정렬
      sort = [{ id: "createdAt", desc: true }];
    }
  } else {
    // 정렬이 없으면 기본 정렬
    sort = [{ id: "createdAt", desc: true }];
  }

  // 플래그 파라미터 파싱
  let flags: string[] = [];
  const flagsParam = searchParams.get("flags");
  if (flagsParam) {
    try {
      flags = JSON.parse(flagsParam);
    } catch (e) {
      console.warn("Invalid flags parameter:", e);
      flags = [];
    }
  }

  // searchParamsCache의 모든 필드를 포함한 입력 객체 생성
  return {
    // 무한 스크롤 관련
    cursor,
    limit,

    // 기본 필터 필드들 (searchParamsCache와 동일)
    itemCode,
    itemName,
    description,
    parentItemCode,
    itemLevel,
    deleteFlag,
    unitOfMeasure,
    steelType,
    gradeMaterial,
    changeDate,
    baseUnitOfMeasure,

    // 고급 필터링
    search,
    filters,
    joinOperator: joinOperator as "and" | "or",
    
    // 정렬
    sort,
    
    // 플래그
    flags,
  };
}

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    
    console.log('API Request URL:', request.url);
    console.log('Search Params:', Object.fromEntries(searchParams.entries()));
    
    // URL 파라미터를 서비스 입력으로 변환
    const input = parseUrlParamsToInfiniteInput(searchParams);
    
    console.log('Parsed Input:', JSON.stringify(input, null, 2));
    
    // 무한 스크롤 서비스 함수 호출
    const result = await getItemsInfinite(input);
    
    console.log('Service Result:', {
      dataCount: result.data.length,
      hasNextPage: result.hasNextPage,
      nextCursor: result.nextCursor,
      total: result.total,
    });
    
    // 응답에 메타데이터 추가
    const response = {
      mode: 'infinite' as const,
      ...result,
      meta: {
        table: 'items',
        displayName: 'Package Items',
        requestedLimit: input.limit || 50,
        actualLimit: Math.min(input.limit || 50, 100),
        maxPageSize: 100,
        cursor: input.cursor || null,
        apiVersion: '1.0',
        timestamp: new Date().toISOString(),
        supportedFields: [
          'itemCode', 'itemName', 'description', 'parentItemCode',
          'itemLevel', 'deleteFlag', 'unitOfMeasure', 'steelType',
          'gradeMaterial', 'changeDate', 'baseUnitOfMeasure'
        ],
        searchableFields: [
          'itemLevel', 'itemCode', 'itemName', 'description', 
          'parentItemCode', 'unitOfMeasure', 'steelType', 
          'gradeMaterial', 'baseUnitOfMeasure', 'changeDate'
        ],
      }
    };

    return NextResponse.json(response);

  } catch (error) {
    console.error("Items infinite API error:", error);
    
    return NextResponse.json({
      mode: 'infinite' as const,
      data: [],
      hasNextPage: false,
      nextCursor: null,
      total: 0,
      error: {
        message: "Failed to fetch items",
        details: error instanceof Error ? error.message : 'Unknown error',
        timestamp: new Date().toISOString(),
        stack: process.env.NODE_ENV === 'development' ? 
          (error instanceof Error ? error.stack : undefined) : 
          undefined,
      }
    }, { 
      status: 500 
    });
  }
}

// OPTIONS 메서드로 API 정보 제공
export async function OPTIONS() {
  return NextResponse.json({
    table: 'items',
    displayName: 'Package Items',
    mode: 'infinite',
    supportedMethods: ['GET'],
    maxPageSize: 100,
    defaultPageSize: 50,
    
    // 지원되는 모든 파라미터
    supportedParams: {
      // 무한 스크롤 관련
      cursor: { type: 'string', description: 'Cursor for pagination' },
      limit: { type: 'number', description: 'Number of items per page', max: 100, default: 50 },
      
      // 기본 필터 필드들
      itemCode: { type: 'string', description: 'Item code filter' },
      itemName: { type: 'string', description: 'Item name filter' },
      description: { type: 'string', description: 'Description filter' },
      parentItemCode: { type: 'string', description: 'Parent item code filter' },
      itemLevel: { type: 'number', description: 'Item level filter', default: 5 },
      deleteFlag: { type: 'string', description: 'Delete flag filter' },
      unitOfMeasure: { type: 'string', description: 'Unit of measure filter' },
      steelType: { type: 'string', description: 'Steel type filter' },
      gradeMaterial: { type: 'string', description: 'Grade material filter' },
      changeDate: { type: 'string', description: 'Change date filter' },
      baseUnitOfMeasure: { type: 'string', description: 'Base unit of measure filter' },
      
      // 고급 필터링
      search: { type: 'string', description: 'Global search across all fields' },
      filters: { type: 'json', description: 'Advanced filters array' },
      joinOperator: { type: 'string', enum: ['and', 'or'], default: 'and' },
      
      // 정렬
      sort: { type: 'json', description: 'Sort configuration array' },
      
      // 플래그
      flags: { type: 'json', description: 'Feature flags array' },
    },
    
    // 사용 예시
    examples: {
      basic: '/api/table/items/infinite?limit=50',
      withSearch: '/api/table/items/infinite?limit=50&search=steel',
      withFilters: '/api/table/items/infinite?limit=50&itemCode=ABC&steelType=carbon',
      withCursor: '/api/table/items/infinite?cursor=123&limit=50',
      withSort: '/api/table/items/infinite?limit=50&sort=[{"id":"itemName","desc":false}]',
      advanced: '/api/table/items/infinite?limit=50&search=test&filters=[{"id":"itemLevel","operator":"eq","value":"1"}]&joinOperator=and&sort=[{"id":"createdAt","desc":true}]'
    },
    
    apiVersion: '1.0',
    documentation: '/docs/api/items/infinite',
    compatibility: {
      searchParamsCache: 'full',
      dataTable: 'full',
      advancedFilters: 'full',
    }
  });
}