group.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const db = require('../models');
  2. module.exports = {
  3. get_all: (req, res, next) => {
  4. return db.Group.findAll()
  5. .then((groups) => res.json(groups))
  6. .catch((err) => next(err));
  7. },
  8. create: (req, res, next) => {
  9. const data = {
  10. title: req.body.title || ''
  11. };
  12. return db.Group.create(data)
  13. .then((group) => res.json(group))
  14. .catch((err) => next(err));
  15. },
  16. get_by_id: (req, res, next) => {
  17. return db.Group.findByPk(req.params.group_id)
  18. .then((group) => {
  19. if (!group) {
  20. throw { status: 404, message: 'Requested Group not found' };
  21. }
  22. return res.json(group);
  23. })
  24. .catch((err) => next(err));
  25. },
  26. update_by_id: (req, res, next) => {
  27. return db.Group.findByPk(req.params.group_id)
  28. .then((group) => {
  29. if (!group) {
  30. throw { status: 404, message: 'Requested Group not found' };
  31. }
  32. Object.assign(group, req.body);
  33. return group.save();
  34. })
  35. .then((group) => res.json(group))
  36. .catch((err) => next(err));
  37. },
  38. delete_by_id: (req, res, next) => {
  39. return db.Group.findByPk(req.params.group_id)
  40. .then((group) => {
  41. if (!group) {
  42. throw { status: 404, message: 'Requested Group not found' };
  43. }
  44. return group.destroy();
  45. })
  46. .then(() => res.status(200).end())
  47. .catch((err) => next(err));
  48. },
  49. get_all_of_person: (req, res, next) => {
  50. return req.person.getGroups()
  51. .then((groups) => res.json(groups))
  52. .catch((err) => next(err));
  53. },
  54. add_to_person: (req, res, next) => {
  55. return db.Group.findByPk(req.params.group_id)
  56. .then((group) => {
  57. if (!group) {
  58. throw { status: 404, message: 'Requested Group not found' };
  59. }
  60. return req.person.addGroup(group);
  61. })
  62. .then(() => res.status(200).end())
  63. .catch((err) => next(err));
  64. },
  65. remove_from_person: (req, res, next) => {
  66. return db.Group.findByPk(req.params.group_id)
  67. .then((group) => {
  68. if (!group) {
  69. throw { status: 404, message: 'Requested Group not found' };
  70. }
  71. return req.person.removeGroup(group);
  72. })
  73. .then(() => res.status(200).end())
  74. .catch((err) => next(err));
  75. }
  76. };