bookmark.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. module.exports = function(crowi, app) {
  2. const debug = require('debug')('growi:routes:bookmark');
  3. const Bookmark = crowi.model('Bookmark');
  4. const Page = crowi.model('Page');
  5. const ApiResponse = require('../util/apiResponse');
  6. const ApiPaginate = require('../util/apiPaginate');
  7. const actions = {};
  8. actions.api = {};
  9. /**
  10. * @api {get} /bookmarks.get Get bookmark of the page with the user
  11. * @apiName GetBookmarks
  12. * @apiGroup Bookmark
  13. *
  14. * @apiParam {String} page_id Page Id.
  15. */
  16. actions.api.get = function(req, res) {
  17. const pageId = req.query.page_id;
  18. Bookmark.findByPageIdAndUserId(pageId, req.user)
  19. .then((data) => {
  20. debug('bookmark found', pageId, data);
  21. const result = {};
  22. result.bookmark = data;
  23. return res.json(ApiResponse.success(result));
  24. })
  25. .catch((err) => {
  26. return res.json(ApiResponse.error(err));
  27. });
  28. };
  29. /**
  30. *
  31. */
  32. actions.api.list = function(req, res) {
  33. const paginateOptions = ApiPaginate.parseOptions(req.query);
  34. const options = Object.assign(paginateOptions, { populatePage: true });
  35. Bookmark.findByUserId(req.user._id, options)
  36. .then((result) => {
  37. return res.json(ApiResponse.success(result));
  38. })
  39. .catch((err) => {
  40. return res.json(ApiResponse.error(err));
  41. });
  42. };
  43. /**
  44. * @api {post} /bookmarks.add Add bookmark of the page
  45. * @apiName AddBookmark
  46. * @apiGroup Bookmark
  47. *
  48. * @apiParam {String} page_id Page Id.
  49. */
  50. actions.api.add = async function(req, res) {
  51. const pageId = req.body.page_id;
  52. const page = await Page.findByIdAndViewer(pageId, req.user);
  53. if (page == null) {
  54. return res.json(ApiResponse.success({ bookmark: null }));
  55. }
  56. const bookmark = await Bookmark.add(page, req.user);
  57. bookmark.depopulate('page');
  58. bookmark.depopulate('user');
  59. const result = { bookmark };
  60. return res.json(ApiResponse.success(result));
  61. };
  62. /**
  63. * @api {post} /bookmarks.remove Remove bookmark of the page
  64. * @apiName RemoveBookmark
  65. * @apiGroup Bookmark
  66. *
  67. * @apiParam {String} page_id Page Id.
  68. */
  69. actions.api.remove = function(req, res) {
  70. const pageId = req.body.page_id;
  71. Bookmark.removeBookmark(pageId, req.user)
  72. .then((data) => {
  73. debug('Bookmark removed.', data); // if the bookmark is not exists, this 'data' is null
  74. return res.json(ApiResponse.success());
  75. })
  76. .catch((err) => {
  77. return res.json(ApiResponse.error(err));
  78. });
  79. };
  80. return actions;
  81. };