activities.js 2.3 KB

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