songs.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const cache = require('./cache');
  3. const db = require('./db');
  4. const io = require('./io');
  5. const utils = require('./utils');
  6. const async = require('async');
  7. module.exports = {
  8. init: function(cb) {
  9. let _this = this;
  10. db.models.song.find({}, (err, songs) => {
  11. if (!err) {
  12. songs.forEach((song) => {
  13. cache.hset('songs', song._id, cache.schemas.song(song));
  14. });
  15. cb();
  16. }
  17. });
  18. },
  19. // Attempts to get the song from Reids. If it's not in Redis, get it from Mongo and add it to Redis.
  20. getSong: function(songId, cb) {
  21. async.waterfall([
  22. (next) => {
  23. cache.hget('songs', songId, next);
  24. },
  25. (song, next) => {
  26. if (song) return next(true, song);
  27. db.models.song.findOne({_id: songId}, next);
  28. },
  29. (song, next) => {
  30. if (song) {
  31. cache.hset('songs', songId, song);
  32. next(true, song);
  33. } else next('Song not found.');
  34. },
  35. ], (err, song) => {
  36. if (err && err !== true) cb(err);
  37. cb(null, song);
  38. });
  39. },
  40. updateSong: (songId, cb) => {
  41. async.waterfall([
  42. (next) => {
  43. db.models.song.findOne({_id: songId}, next);
  44. },
  45. (song, next) => {
  46. if (!song) return next('Song not found.');
  47. cache.hset('songs', songId, song, next);
  48. }
  49. ], (err, song) => {
  50. if (err && err !== true) cb(err);
  51. cb(null, song);
  52. });
  53. }
  54. };