카테고리 없음

라우트 핸들러&서버액션

myinfo7091 2024. 12. 18. 14:11
import { ChampionRotation } from "@/types/ChampionRotation";
import { NextResponse } from "next/server";

export async function GET() {
  const apiKey = process.env.NEXT_PUBLIC_RIOT_API_KEY as string;

  if (!apiKey) {
    return NextResponse.json(
      { error: "API KEY를 찾을 수 없습니다." },
      {
        status: 500,
      }
    );
  }

  try {
    const response = await fetch(
      "https://kr.api.riotgames.com/lol/platform/v3/champion-rotations",
      {
        method: "GET",
        headers: {
          "X-Riot_Token": apiKey,
        },
      }
    );

    if (!response.ok) {
      throw new Error(`API 요청 실패: ${response.status}`);
    }

    const data: ChampionRotation[] = await response.json();
    return NextResponse.json(data);
  } catch (error) {
    console.error("Failed to fetch", error);

    return NextResponse.json(
      { error: "챔피언 정보를 가져오지 못했습니다." },
      { status: 500 }
    );
  }
}
"use server";

import { apiURL } from "@/constants/constants";
import { Champion } from "@/types/Champion";
import { Item } from "@/types/Item";

// 최신 버전 정보
export async function fetchVersion(): Promise<string> {
  const response = await fetch(`${apiURL}/api/versions.json`, {
    method: "GET",
  });

  if (!response.ok) {
    throw new Error(`버전 정보를 불러오지 못했습니다.: ${response.status}`);
  }

  const data: string[] = await response.json();
  return data[0];
}

// 챔피언 목록: ISR(revalidate: 86400)
export async function fetchChampionList(): Promise<Champion[]> {
  const version = await fetchVersion();
  const response = await fetch(
    `${apiURL}/cdn/${version}/data/ko_KR/champion.json`,
    {
      next: {
        revalidate: 86400,
      },
    }
  );

  if (!response.ok) {
    throw new Error(`챔피언 목록을 불러오지 못했습니다.: ${response.status}`);
  }

  const data = await response.json();
  const champions: Champion[] = Object.values(data.data);
  return champions;
}

// 아이템 목록
export async function fetchItems(): Promise<Item[]> {
  const version = await fetchVersion();
  const response = await fetch(`${apiURL}/cdn/${version}/data/ko_KR/item.json`);

  if (!response.ok) {
    throw new Error(`아이템 목록을 불러오지 못했습니다.: ${response.status}`);
  }

  const data = await response.json();
  const items: Item[] = Object.values(data.data);
  return items;
}