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

95 lines
3.1 KiB
TypeScript

// External survey event API.
import { NextRequest, NextResponse } from "next/server";
import { RouteContext } from "@/types/common";
import { errorToResponse } from "@kri/common/http";
import { getClientIp } from "@kri/common/server";
import {
EXTERNAL_ACTION_CODE_BY_SLUG,
ExternalAction,
ExternalEntryType,
ExternalEventBody,
} from "@/types/external";
import {createContactApi} from "@/lib/http-server";
const getHeader = (headers: Headers, name: string): string | null => {
const value = headers.get(name);
return value && value.trim().length > 0 ? value : null;
};
const getEntryType = (headers: Headers): ExternalEntryType => {
return getHeader(headers, "x-entry-type") === "redirect" ? "redirect" : "api";
};
const toExternalAction = (value: string): ExternalAction | null => {
return value in EXTERNAL_ACTION_CODE_BY_SLUG ? (value as ExternalAction) : null;
};
const toRequiredNumber = (value: string): number | null => {
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
};
const buildExternalEventBody = (
req: NextRequest,
action: ExternalAction,
prjctIdx: number,
sid: number,
): ExternalEventBody => {
const pathname = req.nextUrl.pathname;
const h = req.headers;
const actionCode = EXTERNAL_ACTION_CODE_BY_SLUG[action];
return {
actionCode,
prjctIdx,
sid,
meta: {
entryType: getEntryType(h),
action,
actionCode,
pid: String(prjctIdx),
sid: String(sid),
remoteAddr: getHeader(h, "x-orig-ip") || getClientIp(req),
uri: getHeader(h, "x-orig-uri") || pathname,
url: getHeader(h, "x-orig-url") || req.url,
userAgent: getHeader(h, "x-orig-user-agent") || getHeader(h, "user-agent"),
referer: getHeader(h, "x-orig-referer") || getHeader(h, "referer"),
origin: getHeader(h, "x-orig-origin") || getHeader(h, "origin"),
xForwardedFor: getHeader(h, "x-orig-x-forwarded-for") || getHeader(h, "x-forwarded-for"),
forwarded: getHeader(h, "x-orig-forwarded") || getHeader(h, "forwarded"),
},
};
};
const handleExternalEvent = async (req: NextRequest, context: RouteContext) => {
try {
const { searchParams } = req.nextUrl;
const { slug = [] } = await context.params;
const action = toExternalAction((slug[0] ?? "").toLowerCase());
if (slug.length !== 1 || !action) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const prjctIdx = toRequiredNumber((searchParams.get("pid") ?? "").trim());
const sid = toRequiredNumber((searchParams.get("sid") ?? "").trim());
if (!prjctIdx || !sid) {
return NextResponse.json({ message: "pid와 sid는 필수입니다." }, { status: 400 });
}
const body = buildExternalEventBody(req, action, prjctIdx, sid);
const contactApi = await createContactApi();
await contactApi.post(`/list-hist/survey`, body);
return new NextResponse(null, { status: 204 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const GET = handleExternalEvent;
export const POST = handleExternalEvent;