프론트엔드 웹/Next

json 파일에서 필터링해서 보내주는 Next.js API 만들기

세리둥절 2023. 8. 23. 10:37
반응형
import { NextApiRequest, NextApiResponse } from "next";
import abroad from "../../../../data/aptLifestyle/abroad.json";
import { Type } from "../../../../types";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { query: { code } } = req;

  const foundData = (abroad as Type[]).filter(
  	(item) => String(item.code) === (code as string)
   );

//   if (foundData.length === 0) {
//     res.status(404).json("Not Found");
//     return;
//   }

  const shape = (data: Type[]) => {
    return data.map((item: Type) => {
      return {
        column1: `${item.ranking}위`,
        column2: item.name,
        rate: item.rate,
        rank: item.ranking,
        liftRank : item.lift >= 1 && item.lift_ranking,
      };
    });
  };

  res.status(200).json(shape(foundData));
}
반응형