routes.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var Todo = require('./models/todo');
  2. function getTodos(res){
  3. Todo.find(function(err, todos) {
  4. // if there is an error retrieving, send the error. nothing after res.send(err) will execute
  5. if (err)
  6. res.send(err)
  7. res.json(todos); // return all todos in JSON format
  8. });
  9. };
  10. module.exports = function(app) {
  11. // api ---------------------------------------------------------------------
  12. // get all todos
  13. app.get('/api/todos', function(req, res) {
  14. // use mongoose to get all todos in the database
  15. getTodos(res);
  16. });
  17. // create todo and send back all todos after creation
  18. app.post('/api/todos', function(req, res) {
  19. // create a todo, information comes from AJAX request from Angular
  20. Todo.create({
  21. text : req.body.text,
  22. done : false
  23. }, function(err, todo) {
  24. if (err)
  25. res.send(err);
  26. // get and return all the todos after you create another
  27. getTodos(res);
  28. });
  29. });
  30. // delete a todo
  31. app.delete('/api/todos/:todo_id', function(req, res) {
  32. Todo.remove({
  33. _id : req.params.todo_id
  34. }, function(err, todo) {
  35. if (err)
  36. res.send(err);
  37. getTodos(res);
  38. });
  39. });
  40. // application -------------------------------------------------------------
  41. app.get('*', function(req, res) {
  42. res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
  43. });
  44. };