Files
contact-front/src/app/api/list-jobs/[[...slug]]/route.ts

60 lines
3.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { errorToResponse } from '@kri/common/http'
import { createContactApi } from '@/lib/http-server'
import { serverEnv } from '@/lib/env.server'
import { CookieKeys } from '@/store/cookie/cookie-keys'
import type { RouteContext } from '@/types/common'
const project = '[1-9][0-9]*'
const key = '[a-f0-9]{32}'
const getPath = new RegExp(`^${project}/(?:availability|upload-reset-active|my-active|${key}(?:/(?:sid-failures|range-failures|validation-errors|source-file|files/[0-9]+|message-report/(?:batches|preparation-failures)))?)$`)
const postPath = new RegExp(`^${project}/(?:upload|reset|${key}/cancel|mutations/(?:update|assign-reset|assign/[^/]+)|downloads/(?:list|event-history|update-history|item-files)|messages/(?:email|sms|kko))$`)
// The shared HTTP client decodes binary bodies. Forward file bodies as streams instead.
async function forwardFile(req: NextRequest, path: string) {
const token = (await cookies()).get(CookieKeys.AuthToken)?.value
if (!token) return NextResponse.json({ message: '로그인이 필요합니다.' }, { status: 401 })
const headers = new Headers({ Authorization: `Bearer ${token}` })
if (req.method === 'POST') {
const type = req.headers.get('content-type')
if (!type?.startsWith('multipart/form-data;')) return NextResponse.json({ message: '파일 요청 형식이 올바르지 않습니다.' }, { status: 400 })
headers.set('Content-Type', type)
}
const options: RequestInit & { duplex?: 'half' } = {
method: req.method, headers, cache: 'no-store', redirect: 'error',
signal: AbortSignal.any([req.signal, AbortSignal.timeout(300_000)]),
...(req.method === 'POST' ? { body: req.body, duplex: 'half' as const } : {}),
}
const upstream = await fetch(`${serverEnv.API_CONTACT_SERVER.replace(/\/$/, '')}/list/jobs/${path}`, options)
const responseHeaders = new Headers({ 'Cache-Control': 'no-store' })
for (const name of ['Content-Type', 'Content-Disposition', 'Content-Length']) {
const value = upstream.headers.get(name)
if (value) responseHeaders.set(name, value)
}
return new NextResponse(upstream.body, { status: upstream.status, headers: responseHeaders })
}
async function proxy(req: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params
const path = slug.map(encodeURIComponent).join('/')
if (!(req.method === 'GET' ? getPath : postPath).test(path)) return NextResponse.json({ message: '지원하지 않는 작업 경로입니다.' }, { status: 404 })
if (/\/(source-file|files\/[0-9]+|upload)$/.test(path)) return await forwardFile(req, path)
const query = new URLSearchParams()
for (const name of ['offset', 'limit', 'includeResult', 'jobType']) {
const value = req.nextUrl.searchParams.get(name)
if (value !== null) query.set(name, value)
}
const url = `/list/jobs/${path}${query.size ? `?${query}` : ''}`
const api = await createContactApi()
const value = req.method === 'GET'
? await api.get(url, { cache: 'no-store' })
: await api.post(url, await req.json().catch(() => undefined))
return NextResponse.json(value, { headers: { 'Cache-Control': 'no-store' } })
} catch (error: unknown) { return errorToResponse(error) }
}
export const GET = proxy
export const POST = proxy