donal
2018-03-26 6ef0cc963d40c64fb56ba0545c05788535a45895
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
 
var _ = require('lodash');
var Todo = require('./todo.model');
 
// Get list of todos
exports.index = function(req, res) {
  var biscuits;
  Todo.find(function (err, todos) {
    if(err) { return handleError(res, err); }
    return res.status(200).json(todos);
  });
};
 
// Get a single todo
exports.show = function(req, res) {
  if (!handleObjectId(req, res)) return;
  Todo.findById(req.params.id, function (err, todo) {
    if(err) { return handleError(res, err); }
    if(!todo) { return res.status(404).send('Not Found'); }
    return res.json(todo);
  });
};
 
// Creates a new todo in the DB.
exports.create = function(req, res) {
  Todo.create(req.body, function(err, todo) {
    if(err) { return handleError(res, err); }
    return res.status(201).json(todo);
  });
};
 
// Updates an existing todo in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  if (!handleObjectId(req, res)) return;
  Todo.findById(req.params.id.toString(), function (err, todo) {
    if (err) { return handleError(res, err); }
    if(!todo) { return res.status(404).send('Not Found'); }
    var updated = _.merge(todo, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.status(200).json(todo);
    });
  });
};
 
// Deletes a todo from the DB.
exports.destroy = function(req, res) {
  if (!handleObjectId(req, res)) return;
  Todo.findById(req.params.id, function (err, todo) {
    if(err) { return handleError(res, err); }
    if(!todo) { return res.status(404).send('Not Found'); }
    todo.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.status(204).send('No Content');
    });
  });
};
 
function handleError(res, err) {
  return res.status(500).send(err);
}
 
function handleObjectId(req, res) {
  // check if it is a valid ObjectID to prevent cast error
  if (!req.params || !req.params.id || !req.params.id.match(/^[0-9a-fA-F]{24}$/)) {
    res.status(400).send('not a valid mongo object id');
    return false;
  }
  return true;
}