koel/resources/assets/js/stores/favorite.js

107 lines
2.6 KiB
JavaScript
Raw Normal View History

2015-12-13 04:42:28 +00:00
import _ from 'lodash';
import http from '../services/http';
import utils from '../services/utils';
export default {
state: {
songs: [],
2016-01-14 08:02:59 +00:00
length: 0,
fmtLength: '',
2015-12-13 04:42:28 +00:00
},
2016-01-17 14:26:24 +00:00
/**
* Get all songs favorited by the current user.
*
* @return {Array.<Object>}
*/
2015-12-13 04:42:28 +00:00
all() {
return this.state.songs;
},
2015-12-30 04:14:47 +00:00
clear() {
this.state.songs = [];
},
2015-12-13 04:42:28 +00:00
/**
* Toggle like/unlike a song.
* A request to the server will be made.
*
2016-01-07 09:03:38 +00:00
* @param {Object} song
* @param {?Function} cb
2015-12-13 04:42:28 +00:00
*/
toggleOne(song, cb = null) {
2015-12-24 09:59:04 +00:00
// Don't wait for the HTTP response to update the status, just toggle right away.
// This may cause a minor problem if the request fails somehow, but do we care?
song.liked = !song.liked;
2015-12-13 04:42:28 +00:00
2015-12-24 09:59:04 +00:00
if (song.liked) {
this.add(song);
} else {
this.remove(song);
}
2015-12-13 04:42:28 +00:00
2015-12-29 01:35:22 +00:00
http.post('interaction/like', { id: song.id }, () => {
2015-12-13 04:42:28 +00:00
if (cb) {
cb();
}
});
},
/**
* Add a song into the store.
*
2016-01-07 09:03:38 +00:00
* @param {Object} song
2015-12-13 04:42:28 +00:00
*/
add(song) {
this.state.songs.push(song);
},
/**
* Remove a song from the store.
*
2016-01-07 09:03:38 +00:00
* @param {Object} song
2015-12-13 04:42:28 +00:00
*/
remove(song) {
this.state.songs = _.difference(this.state.songs, [song]);
},
/**
* Like a bunch of songs.
*
2016-01-17 14:26:24 +00:00
* @param {Array.<Object>} songs
* @param {?Function} cb
2015-12-13 04:42:28 +00:00
*/
like(songs, cb = null) {
2015-12-24 09:59:04 +00:00
// Don't wait for the HTTP response to update the status, just set them to Liked right away.
// This may cause a minor problem if the request fails somehow, but do we care?
_.each(songs, song => song.liked = true);
2015-12-13 04:42:28 +00:00
this.state.songs = _.union(this.state.songs, songs);
2015-12-29 01:35:22 +00:00
http.post('interaction/batch/like', { ids: _.pluck(songs, 'id') }, () => {
2015-12-13 04:42:28 +00:00
if (cb) {
cb();
}
});
},
/**
* Unlike a bunch of songs.
*
2016-01-17 14:26:24 +00:00
* @param {Array.<Object>} songs
* @param {?Function} cb
2015-12-13 04:42:28 +00:00
*/
unlike(songs, cb = null) {
2015-12-24 09:59:04 +00:00
// Don't wait for the HTTP response to update the status, just set them to Unliked right away.
// This may cause a minor problem if the request fails somehow, but do we care?
_.each(songs, song => song.liked = false);
2015-12-13 04:42:28 +00:00
this.state.songs = _.difference(this.state.songs, songs);
2015-12-29 01:35:22 +00:00
http.post('interaction/batch/unlike', { ids: _.pluck(songs, 'id') }, () => {
2015-12-13 04:42:28 +00:00
if (cb) {
cb();
}
});
},
};