Source: lib/db/comments/reads.js

  1. import { ObjectID } from "bson";
  2. import { getCommentsCollection } from "../mongodb";
  3. import { getPostById } from "../reads";
  4. /**
  5. * Gets all the comments from a publication
  6. *
  7. * @param {string} postId
  8. */
  9. export async function getComments(postId) {
  10. const [collection, post] = await Promise.all([
  11. getCommentsCollection(),
  12. getPostById(postId),
  13. ]);
  14. if (!post) {
  15. console.error({
  16. name: "Post miss",
  17. message: "No publication found to append comment",
  18. });
  19. return;
  20. }
  21. const cursor = collection
  22. .find({ dreamId: ObjectID(postId) })
  23. .sort({ _id: 1 });
  24. const result = await cursor.toArray();
  25. if (result.lenght === 0) {
  26. return null;
  27. }
  28. return result;
  29. }
  30. /**
  31. * Gets all the comments from a user
  32. *
  33. * @param {string} userId
  34. */
  35. export async function getCommentsByUserId(userId) {
  36. const collection = await getCommentsCollection();
  37. const cursor = collection
  38. .find({ userId: ObjectID(userId) })
  39. .sort({ _id: -1 });
  40. const result = await cursor.toArray();
  41. if (result.lenght === 0) {
  42. return null;
  43. }
  44. return result;
  45. }
  46. /**
  47. * Gets a comment on a publication by its id
  48. *
  49. * @param {string} commentId The comment id
  50. */
  51. export async function getCommentById(commentId) {
  52. const collection = await getCommentsCollection();
  53. const cursor = collection.find({ _id: ObjectID(commentId) }).limit(1);
  54. const result = await cursor.toArray();
  55. await cursor.close();
  56. if (result.lenght === 0) {
  57. return null;
  58. }
  59. const data = result[0];
  60. return data;
  61. }
  62. /**
  63. * Checks whether a user has commented on a post or not
  64. *
  65. * @param {string} userName The user name
  66. * @param {string} postId The post id
  67. * @returns {Promise<boolean>}
  68. */
  69. export async function hasCommentedOnPost(userName, postId) {
  70. const collection = await getCommentsCollection();
  71. return (
  72. (await collection
  73. .find({ userName: userName, dreamId: ObjectID(postId) })
  74. .count()) > 0
  75. );
  76. }