activities.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import async from "async";
  2. import CoreClass from "../core";
  3. // let ActivitiesModule;
  4. let DBModule;
  5. let UtilsModule;
  6. class _ActivitiesModule extends CoreClass {
  7. // eslint-disable-next-line require-jsdoc
  8. constructor() {
  9. super("activities");
  10. // ActivitiesModule = this;
  11. }
  12. /**
  13. * Initialises the activities module
  14. *
  15. * @returns {Promise} - returns promise (reject, resolve)
  16. */
  17. initialize() {
  18. return new Promise(resolve => {
  19. DBModule = this.moduleManager.modules.db;
  20. UtilsModule = this.moduleManager.modules.utils;
  21. resolve();
  22. });
  23. }
  24. // TODO: Migrate
  25. /**
  26. * Adds a new activity to the database
  27. *
  28. * @param {object} payload - object that contains the payload
  29. * @param {string} payload.userId - the id of the user who's activity is to be added
  30. * @param {string} payload.activityType - the type of activity (enum specified in schema)
  31. * @param {Array} payload.payload - the details of the activity e.g. an array of songs that were added
  32. * @returns {Promise} - returns promise (reject, resolve)
  33. */
  34. ADD_ACTIVITY(payload) {
  35. return new Promise((resolve, reject) => {
  36. async.waterfall(
  37. [
  38. next => {
  39. DBModule.runJob("GET_MODEL", { modelName: "activity" }, this)
  40. .then(res => next(null, res))
  41. .catch(next);
  42. },
  43. (ActivityModel, next) => {
  44. const activity = new ActivityModel({
  45. userId: payload.userId,
  46. activityType: payload.activityType,
  47. payload: payload.payload
  48. });
  49. activity.save((err, activity) => {
  50. if (err) return next(err);
  51. return next(null, activity);
  52. });
  53. },
  54. (activity, next) => {
  55. UtilsModule.runJob(
  56. "SOCKETS_FROM_USER",
  57. {
  58. userId: activity.userId
  59. },
  60. this
  61. )
  62. .then(response => {
  63. response.sockets.forEach(socket => {
  64. socket.emit("event:activity.create", activity);
  65. });
  66. next();
  67. })
  68. .catch(next);
  69. }
  70. ],
  71. async (err, activity) => {
  72. if (err) {
  73. err = await UtilsModule.runJob(
  74. "GET_ERROR",
  75. {
  76. error: err
  77. },
  78. this
  79. );
  80. reject(new Error(err));
  81. } else {
  82. resolve({ activity });
  83. }
  84. }
  85. );
  86. });
  87. }
  88. }
  89. export default new _ActivitiesModule();