contacts.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. const Contact = require("../model/contact");
  2. const listContacts = async (req, res, next) => {
  3. try {
  4. const userId = req.user.id;
  5. const contacts = await Contact.getList(userId, req.query);
  6. return res.json({
  7. status: "success",
  8. code: 200,
  9. data: {
  10. ...contacts,
  11. },
  12. });
  13. } catch (e) {
  14. next(e);
  15. }
  16. };
  17. const getContactById = async (req, res, next) => {
  18. try {
  19. const id = req.params.id;
  20. const userId = req.user.id;
  21. const contact = await Contact.getById(id, userId);
  22. if (contact)
  23. return res.json({
  24. status: "success",
  25. code: 200,
  26. data: {
  27. contact,
  28. },
  29. });
  30. return res.status(404).json({
  31. status: "error",
  32. code: 404,
  33. data: "Not Found",
  34. });
  35. } catch (e) {
  36. next(e);
  37. }
  38. };
  39. const addContact = async (req, res, next) => {
  40. try {
  41. const contact = req.body;
  42. const userId = req.user.id;
  43. if (contact) {
  44. await Contact.add({ ...contact, owner: userId });
  45. return res.status(201).json({
  46. status: "success",
  47. code: 201,
  48. data: {
  49. contact,
  50. },
  51. });
  52. }
  53. } catch (e) {
  54. next(e);
  55. }
  56. };
  57. const removeContact = async (req, res, next) => {
  58. try {
  59. const id = req.params.id;
  60. const userId = req.user.id;
  61. const contact = await Contact.remove(id, userId);
  62. if (contact) {
  63. return res.json({
  64. status: "success",
  65. code: 200,
  66. data: {
  67. contact,
  68. },
  69. });
  70. } else {
  71. return res.status(404).json({
  72. status: "error",
  73. code: 404,
  74. data: "Not Found",
  75. });
  76. }
  77. } catch (e) {
  78. next(e);
  79. }
  80. };
  81. const updateContact = async (req, res, next) => {
  82. try {
  83. const id = req.params.id;
  84. const userId = req.user.id;
  85. const contact = await Contact.update(id, userId, req.body);
  86. if (contact) {
  87. return res.status(200).json({
  88. status: "success",
  89. code: 200,
  90. data: {
  91. contact,
  92. },
  93. });
  94. } else {
  95. return res.status(404).json({
  96. status: "error",
  97. code: 404,
  98. data: "Not Found",
  99. });
  100. }
  101. } catch (e) {
  102. next(e);
  103. }
  104. };
  105. module.exports = {
  106. listContacts,
  107. getContactById,
  108. addContact,
  109. removeContact,
  110. updateContact,
  111. };