작성
·
206
0
안녕하세요~
게시글 존재 검사 중복로직을 제거해보려고 시도를 해보았습니다.
포스트 존재 확인후 조회한 post객체를 다시
router.post('/:id/like'.. 의 async(req,res,next)=>{} 함수로 넘겨주려고 했으나 방법을 못찾아 async(req,res,next)함수를 감싸는 방식으로 하였습니다.
router.post('/:id/like', isLoggedIn, isPost, asycn(req,res,next,post)) ->이런 방식으로 할 수 있는 방법이 있나요?
isLoggedin 미들웨어 는 단순히 next()로 다음 미들웨어로
넘기는 거라 하셔서 조회된 post 값을 어떻게 다음 미들웨어로 넘기는지 궁금합니다.
//middleware.js
const db = require( '../models' );
exports.isPost = asyncFunc => {
return (async (req, res, next) => {
try {
const post = await db.Post.findOne( {
where: {
id: req.params.id
},
} );
if ( !post ){
return res.status( 404 ).send( '게시글이 존재하지 않습니다.' );
}else{
return await asyncFunc( req, res, next, post );
}
} catch (e) {
console.error(e);
return next( e );
}
});
};
//post.js
router.post( '/:id/like', isLoggedIn, isPost( async (req, res, next, post) => {
try {
console.log( 'post',post );
await post.addLiker( req.user.id );
res.json( { userId: req.user.id } );
} catch (e) {
console.error( e );
next( e );
}
} ) );
답변 1
2
다음 미들웨어로 데이터를 넣을 때는 보통 req 객체의 속성으로 넣습니다. req.posts = posts;한 후 다음 미들웨어에서 req.posts로 받으면 됩니다.