phone.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const db = require('../models');
  2. module.exports = {
  3. get_all: (req, res, next) => {
  4. let where = {};
  5. if (req.query.type) {
  6. where.type = req.query.type;
  7. }
  8. return req.person.getPhones({
  9. order: [ 'type' ],
  10. where
  11. })
  12. .then((phones) => res.json(phones))
  13. .catch((err) => next(err));
  14. },
  15. get_by_id: (req, res, next) => {
  16. return req.person.getPhones({
  17. where: {
  18. id: req.params.phone_id
  19. }
  20. })
  21. .then((phones) => {
  22. if (phones.length === 0) {
  23. throw { status: 404, message: 'Requested Phone not found' };
  24. }
  25. return res.json(phones[0]);
  26. })
  27. .catch((err) => next(err));
  28. },
  29. create: (req, res, next) => {
  30. const data = {
  31. number: req.body.number || '',
  32. type: req.body.type || 'home'
  33. };
  34. return req.person.createPhone(data)
  35. .then((phone) => res.json(phone))
  36. .catch((err) => next(err));
  37. },
  38. update_by_id: (req, res, next) => {
  39. return req.person.getPhone({
  40. where: {
  41. id: req.params.phone_id
  42. }
  43. })
  44. .then((phones) => {
  45. if (phones.length === 0) {
  46. throw { status: 404, message: 'Requested Phone not found' };
  47. }
  48. Object.assign(phones[0], req.body);
  49. return phones[0].save();
  50. })
  51. .then((phone) => res.json(phone))
  52. .catch((err) => next(err));
  53. },
  54. delete_by_id: (req, res, next) => {
  55. return req.person.getPhones({
  56. where: {
  57. id: req.params.phone_id
  58. }
  59. })
  60. .then((phones) => {
  61. if (phones.length === 0) {
  62. throw { status: 404, message: 'Requested Phone not found' };
  63. }
  64. return phones[0].destroy();
  65. })
  66. .then(() => res.status(200).end())
  67. .catch((err) => next(err));
  68. }
  69. };