songs.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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: cb => {
  9. db.models.song.find({}, (err, songs) => {
  10. if (!err) {
  11. songs.forEach((song) => {
  12. cache.hset('songs', song._id, cache.schemas.song(song));
  13. });
  14. cb();
  15. }
  16. });
  17. },
  18. // Attempts to get the song from Reids. If it's not in Redis, get it from Mongo and add it to Redis.
  19. getSong: function(_id, cb) {
  20. async.waterfall([
  21. (next) => {
  22. cache.hget('songs', _id, next);
  23. },
  24. (song, next) => {
  25. if (song) return next(true, song);
  26. db.models.song.findOne({ _id }, next);
  27. },
  28. (song, next) => {
  29. if (song) {
  30. cache.hset('songs', _id, song);
  31. next(true, song);
  32. } else next('Song not found.');
  33. },
  34. ], (err, song) => {
  35. if (err && err !== true) return cb(err);
  36. cb(null, song);
  37. });
  38. },
  39. updateSong: (_id, cb) => {
  40. async.waterfall([
  41. (next) => {
  42. db.models.song.findOne({ _id }, next);
  43. },
  44. (song, next) => {
  45. if (!song) return next('Song not found.');
  46. cache.hset('songs', _id, song, next);
  47. }
  48. ], (err, song) => {
  49. if (err && err !== true) cb(err);
  50. cb(null, song);
  51. });
  52. }
  53. };