티스토리 뷰

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));
});

실행

댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함