Source: pages/api/data/comments.js

  1. /** @module pages/api/data/comments */
  2. import { getServerSession } from "../../../lib/auth";
  3. import { createComment, deleteComment } from "../../../lib/db/writes";
  4. import {
  5. BAD_REQUEST,
  6. METHOD_NOT_ALLOWED,
  7. SERVER_ERROR,
  8. FORBIDDEN,
  9. } from "../../../lib/errors";
  10. /**
  11. * This is the API route for managing comments.
  12. * It supports POST and DELETE, allowing users to create and delete their own comments.
  13. * Comments cannot be edited, and dream owners cannot delete comments from others (this is likely
  14. * changing in the near future).
  15. */
  16. function commentsHandler(req, res) {
  17. switch (req.method) {
  18. case "POST":
  19. return post(req, res);
  20. case "DELETE":
  21. return del(req, res);
  22. default:
  23. res.setHeader("Allow", ["POST", "DELETE"]);
  24. res.status(405).end(METHOD_NOT_ALLOWED);
  25. return res;
  26. }
  27. }
  28. /**
  29. * @private
  30. */
  31. async function post(req, res) {
  32. const session = await getServerSession(req, res);
  33. if (!session) {
  34. res.status(403).end(FORBIDDEN);
  35. return res;
  36. }
  37. if (!req.body?.comment || !req.body.dreamId) {
  38. res.status(400).end(BAD_REQUEST);
  39. return res;
  40. }
  41. const data = {
  42. comment: req.body.comment,
  43. dreamId: req.body.dreamId,
  44. session,
  45. };
  46. try {
  47. const result = await createComment(data);
  48. const objectId = result.insertedId.toString();
  49. res.setHeader("Content-Type", "application/json");
  50. res.status(201).send({ objectId });
  51. return res;
  52. } catch (error) {
  53. console.error({
  54. error,
  55. service: "api",
  56. pathname: "/api/data/comments",
  57. method: "post",
  58. });
  59. res.status(500).end(SERVER_ERROR);
  60. return res;
  61. }
  62. }
  63. /**
  64. * @private
  65. */
  66. async function del(req, res) {
  67. const session = await getServerSession(req, res);
  68. if (!session) {
  69. res.status(403).end(FORBIDDEN);
  70. return res;
  71. }
  72. if (!req.body?.commentId || !req.body?.dreamId) {
  73. res.status(400).end(BAD_REQUEST);
  74. return res;
  75. }
  76. try {
  77. const result = await deleteComment(req.body.commentId, req.body.dreamId);
  78. res.setHeader("Content-Type", "application/json");
  79. res.status(200).send(result);
  80. return res;
  81. } catch (error) {
  82. console.error({
  83. error,
  84. service: "api",
  85. pathname: "/api/data/comments",
  86. method: "delete",
  87. });
  88. res.status(500).end(SERVER_ERROR);
  89. return res;
  90. }
  91. }
  92. export default commentsHandler;