activities.js 2.1 KB

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