본문 바로가기

잊고 살았던 node.js 라우터 미들웨어 동작방식

(프론트엔드 이슈는 아니지만 잘 잊어먹고 개발하기 쉬워서 급하게 메모ㅠㅠ)

 

상황

1. Server To Server로 본 api 호출 전 유저 검증 api를 미들웨어로 추가함 

const api = axios.create()

const userValidator = (apiKey) => async (ctx, next) => {
    try {
        const {
          request: {body},
    	} = ctx
        
        const params = {
          apiKey,
          requestParams: {
            ...body
          }
        }
        await api.post(`${API_URL}/api/user/validation`, params)
        await next()
    } catch (err) {
        const httpStatus = err.response.status || 500

        ctx.body = createErrorResponse({
            abnormalAccess: httpStatus === 403,
        })
    }
}

router.post(
    '/api/agreement',
    userValidator('A1'),
    async (ctx) => {
        const {
            request: {body, header},
        } = ctx

        /** server to server */

        ctx.body = createSuccessResponse()
    },
)

2. /api/agreement api 호출 시 미들웨어 catch문에 걸려 에러 응답 받음

{
  code: '01',
  message: '에러',
  result: {
    abnormalAccess: false
  }
}

3. 당연히 미들웨어에서 호출한 유저 검증 api 오류일거라고 생각하고 로그 확인

4. 200 정상 응답으로 떨어짐

5. 알고보니 /api/agreement에서 호출한 본 api 오류였음

 

미들웨어 동작 방식에 대해 내가 오해하고 있는 부분이 있어 관련 내용을 StackOverflow에서 찾았다.

Why do we await next when using koa routers?

 

next()는 미들웨어 job을 완전히 종료하고(콜스택에서 pop되고) 실행되는게 아니라 다른 cb의 job을 추가하고 작업이 완료되면 (다음 next가 보이지 않으면) 미들웨어의 job으로 돌아온다.

 

마치 중첩된 함수를 호출하는것처럼 동작한다는 것을 잊지 말자 ㅠㅠ

'Today I Learn > Nodejs' 카테고리의 다른 글

keepalive 설정  (0) 2021.11.23
이벤트 루프와 process.nextTick() 이해하기  (0) 2021.03.08