person_ctrl.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const db = require('../models');
  2. module.exports = {
  3. get_all(req, res, next) {
  4. let param = {
  5. order: ['lastname']
  6. };
  7. if (req.query.lastname) {
  8. param.where = {
  9. lastname: req.query.lastname
  10. };
  11. }
  12. db.Person.findAll(param).then(persons => {
  13. res.json(persons)
  14. }) .catch(error => {
  15. next(error);
  16. })
  17. },
  18. create(req, res, next) {
  19. if (req.body.firstname == undefined || req.body.lastname == undefined) {
  20. throw "Un des éléments est vide";
  21. }
  22. return db.Person.create({lastname: req.body.lastname, firstname: req.body.firstname}).then(p =>
  23. res.json(p)
  24. ) .catch(function (error) {
  25. next(error);
  26. })
  27. },
  28. get_by_id(req, res, next) {
  29. db.Person.findByPk(req.params.person_id).then(persons => {
  30. if (!persons) {
  31. throw { status: 404, message: "Pas bonne id" }
  32. }
  33. res.json(persons)
  34. }) .catch(function (error) {
  35. next(error);
  36. })
  37. },
  38. update_by_id(req, res, next) {
  39. db.Person.findByPk(req.params.person_id).then(person => {
  40. if (!person) {
  41. throw "Pas bonne id";
  42. } else {
  43. person.update(req.body)
  44. .then(
  45. res.send("ok")
  46. )
  47. }
  48. }) .catch(function (error) {
  49. next(error);
  50. })
  51. },
  52. delete_by_id(req, res, next) {
  53. db.Person.destroy({
  54. where: {
  55. id: req.params.person_id
  56. }
  57. }) .then(data => {
  58. if (!data) {
  59. throw "Pas bonne id"
  60. }
  61. res.send("fait")}) .catch(function (error) {
  62. next(error);
  63. })
  64. },
  65. load_by_id(req, res, next) {
  66. db.Person.findByPk(req.params.person_id).then(person => {
  67. if (!person) {
  68. throw { status: 404, message: "Pas bonne id" }
  69. }
  70. req.person = person;
  71. next();
  72. }) .catch(function (error) {
  73. next(error);
  74. })
  75. }
  76. };