Handler function 고차함수

yonghee·2022년 6월 13일
0

baechu-market

목록 보기
18/32
post-thumbnail
//Login.ts
export default async function handler(
	req: NextApiRequest,
    res: NextApiResponse
) {
	if(req.method !== "POST") {
    res.status(401).end();
    }
  	res.status(200).end();
}

Login POST 요청을 보내고 데이터를 받는 Login.ts 이다.

이번 웹사이트를 만들며 시도해보는 것들 중 하나인 고차함수를 활용해볼 생각이다.

고차함수(Higher Order Function(HOF))이란?
하나 이상의 함수를 인자로 받고, 결과로 함수를 리턴합니다. 다시 말해 함수가 또 하나의 함수를 다루는 함수입니다.

고차함수를 사용하는 이유는 GET POST DELETE PUT 등 요청을 할 때마다 이 요청을 다루는 function 컴포넌트를 활용 및 handler()를 실행 하기 전 요청한 메서드가 유효한지 판별하기 위함이다.

Handler 고차함수

//Loing.ts
import { NextApiRequest, NextApiResponse } from "next";
import client from "../../../libs/server/client";
import Handler from "../../../libs/server/Handler";

async function handler(req: NextApiRequest, res: NextApiResponse) {
  //if(req.method !== "POST") {
    //res.status(401).end();
    //}
  console.log(req.body);  
  return res.status(200).end();
}
export default Handler("POST", handler);

//Handler.ts
import { NextApiRequest, NextApiResponse } from "next";

export default function Handler(
  method: "GET" | "POST" | "DELETE",
   //어떤 타입이 들어 올지 타입스크립트 유니온 타입을 지정하였다.
  fn: (req: NextApiRequest, res: NextApiResponse) => void
) {
  return async function (req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== "POST") {
      return res.status(405).end();
    }
    try {
      await fn(req, res);
    } catch (error) {
      console.log(error);
      return res.status(500).json({ error });
    }
  };
}

실행하게 되면 직관적인 로직

async function handler(req: NextApiRequest, res: NextApiResponse) {
  //if(req.method !== "POST") {
    //res.status(401).end();
    //}
  console.log(req.body);  
  return res.status(200).end();
}
export default async function (req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== "POST") {
      return res.status(405).end();
    }
    try {
      await handler(req, res);
    } catch (error) {
      console.log(error);
      return res.status(500).json({ error });
    }
  };

아마 이런 형태가 될 것이다.


공식 홈페이지에 나와있듯이 req.method를 사용하여 들어온 요청이 유효한지 판별이 가능하다 POST 요청이 제대로 들어오면 두번째 파라미터 fn 즉 handelr()을 실행하게 된다. 고차 함수 활용한 로직은 문법으로는 배웠지만 웹사이트 개발하는데는 처음 시도하는 것이라 익숙하지는 않지만 앞으로도 어떤 로직이 실행 되기전에 handle 역할을 하는 방식은 계속 사용하는 습관을 가져야 겠다.

profile
필요할 때 남기는 날것의 기록 공간

0개의 댓글