Advertisement
Guest User

Untitled

a guest
Oct 16th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. /** Application Dependencies */
  2. var express = require('express');
  3. var mysql = require('mysql');
  4.  
  5. /** New Application ENV OBJ */
  6. var app = express();
  7.  
  8. /** Initiate Mysql Connection */
  9. var connection = mysql.createConnection({
  10. host: 'localhost',
  11. user: 'root',
  12. database: 'todo_demo',
  13. password: 'batata'
  14. });
  15.  
  16. connection.connect();
  17.  
  18. /** Actions */
  19. app.get('/', function(req, res) {
  20. res.send('<h1>Todo Service</h1>');
  21. });
  22.  
  23. /** get all todos */
  24. app.get('/api/todo', function(req, res) {
  25. var results;
  26. connection.query('SELECT * from todos where is_done = \'0\'', function(
  27. err, rows, fields) {
  28. if (err) throw err;
  29.  
  30. results = rows;
  31. res.type('application/json');
  32. res.send(results);
  33. });
  34. });
  35.  
  36. /** add new todo */
  37. app.post('/api/todo', function(req, res) {
  38. connection.query('INSERT INTO todos (title,added_on) VALUES(\'' + req.body
  39. .title + '\',NOW())',
  40. function(err, result) {
  41. if (err) throw err;
  42.  
  43. if (result)
  44. res.type('application/json');
  45. res.send([{
  46. "added": 1
  47. }]);
  48. });
  49. });
  50.  
  51. /** Update a Todo */
  52. app.put('/api/todo/:id', function(req, res) {
  53. connection.query(
  54. 'UPDATE todos SET is_done = 1, ended_on = NOW() where id = ' + req.params
  55. .id,
  56. function(err, result) {
  57. if (err) throw err;
  58.  
  59. if (result)
  60. res.type('application/json');
  61. res.send([{
  62. "updated": 1
  63. }]);
  64. });
  65. });
  66.  
  67. /** Delete a TODO */
  68. app.delete('/api/todo/:id', function(req, res) {
  69. connection.query('DELETE from todos where id = ' + req.params.id,
  70. function(err, result) {
  71. if (err) throw err;
  72.  
  73. if (result)
  74. res.type('application/json');
  75. res.send([{
  76. "deleted": 1
  77. }]);
  78. });
  79. });
  80.  
  81. app.listen(80);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement