본문 바로가기
All Side/Runtime > NodeJS

[express] middleware 결과 다음으로 넘겨주기 - next()에 parameters 넣어주기?!

by developerBeluga 2023. 3. 8.
728x90
반응형

 

 

중복코드 없애기 = middleware 사용하기

A, B, C API가 있다.

모두 동일하게 먼저 User라는 데이터가 있는지 확인한다고 하자.

그럼 A, B, C API를 담당하는 router에 User를 조회하는 프로세스가 사용될 것이다.

 

개발자란 동일한 코드를 최대한 사용하지 않는다가 나의 개발론이기 때문에 매우 거슬렀다.

그래서 사용한게 middleware다!

middleware를 이용하면 다음 미들웨어로 현재 요청을 넘길 수 있다.

 

더 자세한 것은 공식문서에서보자.

https://expressjs.com/en/guide/using-middleware.html

 

Using Express middleware

Using middleware Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls. Middleware functions are functions that have access to the request ob

expressjs.com

 

 

 

next()에 parameters 넣어주기?!

이미 아는 사람들이라면 제목을 보고 어그로 끈다고 할 수 있다.

 

왜냐하면 next()엔 err 밖에 넣지 못하기 때문이다.

그럼 어떻게 다음 미들웨어에 현재 데이터를 넘겨줄 수 있을까? 🤔

 

 

 

req에 넣어줘!

export const a = async (req: Request, res: Response, next: NextFunction) => {
  const userData = await User.find();
  // 아래 주목!!
  req.body.user = userData;
  next();
};

 

req에 넣어주면 다음 미들웨어에서 req.body.text하면 textData가 잘 나온다!

 

export const b = async (req: Request, res: Response, next: NextFunction) => {
   const { name, age } = req.body.user;
   console.log('req.body.user', req.body.user);
};

콘솔로 찍어보면 DB 정보들이 잘 나온것을 알 수 있다.

앞으로 User 정보를 조회해야하는 라우터라면 굳이 User DB를 조회하는 코드 대신 a 미들웨어를 넣어주면 된다!

 

import { a } from './middleware';
import { b } from './controllers';

// 라우터에 미들웨어 a 넣어주기
router.get('/user/find', a, b);

라우터에 미들웨어 a를 넣어주면 된다.

 

 

 

fin.

 

 

 

 

728x90
반응형

댓글