onsitesurvey/src/app/api/qna/service.ts

90 lines
3.0 KiB
TypeScript

import { SessionData } from '@/types/Auth'
import { CommonCode } from '@/types/Inquiry'
import { ERROR_MESSAGE } from '@/hooks/useAlertMsg'
import { HttpStatusCode } from 'axios'
import { ApiError } from 'next/dist/server/api-utils'
export class QnaService {
private session?: SessionData
constructor(session?: SessionData) {
this.session = session
}
/**
* @description API ROUTE 에러 처리
* @param {any} error 에러 객체
* @returns {ApiError} 에러 객체
*/
private handleRouteError(error: any): ApiError {
console.error('❌ API ROUTE ERROR : ', error)
return new ApiError(error.response.status, error.response.data.result.message ?? ERROR_MESSAGE.FETCH_ERROR)
}
/**
* @description 비동기 함수 try-catch 처리 함수
* @param {() => Promise<any>} func 비동기 함수
* @returns {Promise<ApiError | any>} 에러 객체 또는 함수 결과
*/
async tryFunction(func: () => Promise<any>, isFile?: boolean): Promise<ApiError | any> {
if (this.session !== undefined && !this.session?.isLoggedIn) {
return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGE.UNAUTHORIZED)
}
try {
const response = await func()
if (isFile) return response
return this.handleResult(response)
} catch (error) {
return this.handleRouteError(error)
}
}
/**
* @description 함수 결과 처리 함수
* @param {any} result 함수 결과
* @returns {ApiError | any} 에러 객체 또는 함수 결과
*/
private handleResult(response: any): ApiError | any {
if (response.status === HttpStatusCode.Ok) {
if (response.data.data !== null) return response.data
return new ApiError(HttpStatusCode.NotFound, ERROR_MESSAGE.NOT_FOUND)
}
return new ApiError(response.result.code, response.result.message)
}
/**
* @description 문의 유형 타입 목록 조회
* @param {string[]} responseList 문의 유형 타입 목록
* @returns {CommonCode[]} 문의 유형 타입 목록
*/
getInquiryTypeList(responseList: string[]): CommonCode[] {
const codeList: CommonCode[] = []
responseList.forEach((item: any) => {
if (item.headCd === '204200' || item.headCd === '204300' || item.headCd === '204400') {
codeList.push({
headCd: item.headCd,
code: item.code,
name: item.codeJp,
refChar1: item.refChr1,
})
}
})
return codeList
}
/**
* @description 문의 목록 조회 파라미터 처리
* @param {URLSearchParams} searchParams URLSearchParams 객체
* @returns {Record<string, string>} 문의 목록 조회 파라미터
*/
getSearchParams(searchParams: URLSearchParams): Record<string, string> {
const params: Record<string, string> = {}
searchParams.forEach((value, key) => {
const match = key.match(/inquiryListRequest\[(.*)\]/)
if (match) {
params[match[1]] = value
} else {
params[key] = value
}
})
return params
}
}