bookmark.js 2.5 KB

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