playlists.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. const db = require('../db');
  3. const io = require('../io');
  4. const cache = require('../cache');
  5. const utils = require('../utils');
  6. const hooks = require('./hooks');
  7. const async = require('async');
  8. const playlists = require('../playlists');
  9. module.exports = {
  10. indexForUser: (session, createdBy, cb) => {
  11. db.models.playlist.find({ createdBy }, (err, playlists) => {
  12. if (err) throw err;
  13. cb({
  14. status: 'success',
  15. data: playlists
  16. });
  17. });
  18. },
  19. create: (session, data, cb) => {
  20. async.waterfall([
  21. (next) => {
  22. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  23. },
  24. // check the cache for the playlist
  25. (next) => cache.hget('playlists', data._id, next),
  26. // if the cached version exist
  27. (playlist, next) => {
  28. if (playlist) return next({ 'status': 'failure', 'message': 'A playlist with that id already exists' });
  29. db.models.playlist.findOne({ _id: data._id }, next);
  30. },
  31. (playlist, next) => {
  32. if (playlist) return next({ 'status': 'failure', 'message': 'A playlist with that id already exists' });
  33. const { _id, displayName, songs, createdBy } = data;
  34. db.models.playlist.create({
  35. _id,
  36. displayName,
  37. songs,
  38. createdBy,
  39. createdAt: Date.now()
  40. }, next);
  41. }
  42. ], (err, playlist) => {
  43. if (err) {console.log(err); return cb({ 'status': 'failure', 'message': 'Something went wrong'});}
  44. cache.pub('playlist.create', data._id);
  45. return cb(null, { 'status': 'success', 'message': 'Successfully created playlist' });
  46. });
  47. },
  48. getPlaylist: (session, id, cb) => {
  49. playlists.getPlaylist(id, (err, playlist) => {
  50. if (err == null) return cb({
  51. status: 'success',
  52. data: playlist
  53. });
  54. });
  55. },
  56. update: (session, _id, playlist, cb) => {
  57. db.models.playlist.findOneAndUpdate({ _id }, playlist, { upsert: true }, (err, data) => {
  58. if (err) throw err;
  59. return cb({ status: 'success', message: 'Playlist has been successfully updated', data });
  60. });
  61. },
  62. updateDisplayName: (session, _id, displayName, cb) => {
  63. db.models.playlist.findOneAndUpdate({ _id }, { displayName }, { upsert: true }, (err, data) => {
  64. if (err) throw err;
  65. return cb({ status: 'success', message: 'Playlist has been successfully updated', data });
  66. });
  67. },
  68. remove: (session, _id, cb) => {
  69. db.models.playlist.remove({ _id });
  70. }
  71. };