summaryrefslogtreecommitdiff
path: root/app/api/juso/route.ts
blob: 258e51d30bf13b3219e88e78b3932606b8b3946f (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
"use server";

import { NextRequest, NextResponse } from "next/server";

const JUSO_URL = "https://business.juso.go.kr/addrlink/addrLinkUrl.do";

export async function GET() {
  const confmKey = process.env.JUSO_API_KEY || "";
  const returnUrl = `${process.env.NEXT_PUBLIC_BASE_URL || ""}/api/juso`;
  const resultType = "4";

  const html = `
    <!doctype html>
    <html lang="ko">
    <head><meta charset="utf-8" /></head>
    <body onload="document.getElementById('jusoForm').submit();">
      <form id="jusoForm" name="jusoForm" method="post" action="${JUSO_URL}">
        <input type="hidden" name="confmKey" value="${confmKey}" />
        <input type="hidden" name="returnUrl" value="${returnUrl}" />
        <input type="hidden" name="resultType" value="${resultType}" />
      </form>
    </body>
    </html>
  `;

  return new NextResponse(html, {
    status: 200,
    headers: { "Content-Type": "text/html; charset=utf-8" },
  });
}

export async function POST(req: NextRequest) {
  const formData = await req.formData();

  const zipNo = String(formData.get("zipNo") || "");
  const roadAddrPart1 = String(formData.get("roadAddrPart1") || "");
  const roadAddrPart2 = String(formData.get("roadAddrPart2") || "");
  const addrDetail = String(formData.get("addrDetail") || "");

  const origin = process.env.NEXT_PUBLIC_BASE_URL || "*";

  const script = `
    <script>
      (function() {
        try {
          const payload = {
            zipNo: ${JSON.stringify(zipNo)},
            roadAddrPart1: ${JSON.stringify(roadAddrPart1)},
            roadAddrPart2: ${JSON.stringify(roadAddrPart2)},
            addrDetail: ${JSON.stringify(addrDetail)}
          };
          if (window.opener && !window.opener.closed) {
            window.opener.postMessage({ type: "JUSO_SELECTED", payload }, "${origin}");
          }
        } catch (e) {
          console.error(e);
        } finally {
          window.close();
        }
      })();
    </script>
  `;

  return new NextResponse(script, {
    status: 200,
    headers: { "Content-Type": "text/html; charset=utf-8" },
  });
}