koel/resources/assets/js/stores/favoriteStore.ts

50 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-06-10 10:47:46 +00:00
import { reactive } from 'vue'
2022-07-22 22:19:42 +00:00
import { differenceBy, unionBy } from 'lodash'
import { http } from '@/services'
2022-04-20 09:37:22 +00:00
import { arrayify } from '@/utils'
2022-06-10 10:47:46 +00:00
import { songStore } from '@/stores'
2022-04-15 14:24:30 +00:00
export const favoriteStore = {
2022-04-21 16:06:45 +00:00
state: reactive({
2022-07-22 22:19:42 +00:00
songs: [] as Song[]
2022-04-21 16:06:45 +00:00
}),
2022-04-15 14:24:30 +00:00
2022-04-21 16:06:45 +00:00
async toggleOne (song: Song) {
2022-04-15 14:24:30 +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
song.liked ? this.add(song) : this.remove(song)
await http.post<Song>('interaction/like', { song: song.id })
2022-04-15 14:24:30 +00:00
},
2022-04-21 16:06:45 +00:00
add (songs: Song | Song[]) {
2022-07-22 21:56:13 +00:00
this.state.songs = unionBy(this.state.songs, arrayify(songs), 'id')
2022-04-15 14:24:30 +00:00
},
2022-04-21 16:06:45 +00:00
remove (songs: Song | Song[]) {
2022-07-22 21:56:13 +00:00
this.state.songs = differenceBy(this.state.songs, arrayify(songs), 'id')
2022-04-15 14:24:30 +00:00
},
2022-04-21 16:06:45 +00:00
async like (songs: Song[]) {
2022-04-15 14:24:30 +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?
2022-06-10 10:47:46 +00:00
songs.forEach(song => (song.liked = true))
2022-04-15 14:24:30 +00:00
this.add(songs)
await http.post('interaction/batch/like', { songs: songs.map(song => song.id) })
2022-04-15 14:24:30 +00:00
},
2022-04-21 16:06:45 +00:00
async unlike (songs: Song[]) {
2022-06-10 10:47:46 +00:00
songs.forEach(song => (song.liked = false))
2022-04-15 14:24:30 +00:00
this.remove(songs)
await http.post('interaction/batch/unlike', { songs: songs.map(song => song.id) })
2022-06-10 10:47:46 +00:00
},
async fetch () {
this.state.songs = songStore.syncWithVault(await http.get<Song[]>('songs/favorite'))
2022-10-13 15:18:47 +00:00
return this.state.songs
2022-04-15 14:24:30 +00:00
}
}