Programming/Node.js
Node.js : Controller
파란크리스마스
2019. 3. 2. 00:16
728x90
출처
/api/user/user.ctrl.js
/* api 로직 */ let users = [ {id: 1, name: 'jinbro'}, {id: 2, name: 'jinhyung'}, {id: 3, name: 'park'} ]; let index = function(req, res) { if(!req.query.limit){ res.json(users); } else { const limit = parseInt(req.query.limit, 10); if(isNaN(limit)){ return res.status(400).end(); } res.json(users.slice(0, limit)); } }; let read = function(req, res) { const id = parseInt(req.params.id, 10); console.log("id = " + id); if(isNaN(id)) { return res.status(400).end(); } const user = users.filter((user) => { return user.id === id; })[0]; if(!user) { return res.status(404).end(); } res.json(user); }; module.exports = { index: index, read: read //create: create, //update: update, //destroy: destroy };
/api/user/index.js
const express = require('express'); const router = express.Router(); const controller = require('./user.ctrl'); /* user 라우팅 로직 */ router.get('/', controller.index); router.get('/:id', controller.read); //router.post('/', controller.create); //router.put('/:id', controller.update); //router.delete('/:id', controller.destroy); module.exports = router;
/app.js
/* use router class */ const user = require('./api/user/index.js'); /* /users 요청을 모두 /user/index.js로 */ app.use('/users', user); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); });
실행