playlists.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const cache = require('./cache');
  3. const db = require('./db');
  4. const async = require('async');
  5. module.exports = {
  6. /**
  7. * Initializes the playlists module, and exits if it is unsuccessful
  8. *
  9. * @param {Function} cb - gets called once we're done initializing
  10. */
  11. init: cb => {
  12. async.waterfall([
  13. (next) => {
  14. db.models.playlist.find({}, next);
  15. },
  16. (playlists, next) => {
  17. async.each(playlists, (playlist, next) => {
  18. cache.hset('playlists', playlist._id, cache.schemas.playlist(playlist), next);
  19. }, next);
  20. }
  21. ], (err) => {
  22. if (err) {
  23. console.log("FAILED TO INITIALIZE PLAYLISTS. ABORTING.");
  24. process.exit();
  25. } else {
  26. cb();
  27. }
  28. });
  29. },
  30. /**
  31. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  32. *
  33. * @param {String} playlistId - the id of the playlist we are trying to get
  34. * @param {Function} cb - gets called once we're done initializing
  35. */
  36. getPlaylist: (playlistId, cb) => {
  37. async.waterfall([
  38. (next) => {
  39. cache.hget('playlists', playlistId, next);
  40. },
  41. (playlist, next) => {
  42. if (playlist) return next(true, playlist);
  43. db.models.playlist.findOne({ _id: playlistId }, next);
  44. },
  45. (playlist, next) => {
  46. if (playlist) {
  47. cache.hset('playlists', playlistId, playlist);
  48. next(true, playlist);
  49. } else next('Playlist not found');
  50. },
  51. ], (err, playlist) => {
  52. if (err && err !== true) return cb(err);
  53. else cb(null, playlist);
  54. });
  55. },
  56. /**
  57. * Gets a playlist from id from Mongo and updates the cache with it
  58. *
  59. * @param {String} playlistId - the id of the playlist we are trying to update
  60. * @param {Function} cb - gets called when an error occurred or when the operation was successful
  61. */
  62. updatePlaylist: (playlistId, cb) => {
  63. async.waterfall([
  64. (next) => {
  65. db.models.playlist.findOne({ _id: playlistId }, next);
  66. },
  67. (playlist, next) => {
  68. if (!playlist) return next('Playlist not found');
  69. cache.hset('playlists', playlistId, playlist, next);
  70. }
  71. ], (err, playlist) => {
  72. if (err && err !== true) cb(err);
  73. cb(null, playlist);
  74. });
  75. }
  76. };