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

58 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-04-15 14:24:30 +00:00
import { difference, union } from 'lodash'
2022-04-24 08:50:45 +00:00
import { httpService } from '@/services'
2022-04-20 09:37:22 +00:00
import { arrayify } from '@/utils'
2022-04-21 16:06:45 +00:00
import { reactive } from 'vue'
2022-04-15 14:24:30 +00:00
export const favoriteStore = {
2022-04-21 16:06:45 +00:00
state: reactive({
2022-04-15 14:24:30 +00:00
songs: [] as Song[],
length: 0,
fmtLength: ''
2022-04-21 16:06:45 +00:00
}),
2022-04-15 14:24:30 +00:00
2022-04-21 16:06:45 +00:00
get all () {
2022-04-15 14:24:30 +00:00
return this.state.songs
},
set all (value: Song[]) {
this.state.songs = value
},
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)
2022-04-24 08:50:45 +00:00
await httpService.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-04-20 09:37:22 +00:00
this.all = union(this.all, arrayify(songs))
2022-04-15 14:24:30 +00:00
},
2022-04-21 16:06:45 +00:00
remove (songs: Song | Song[]) {
2022-04-20 09:37:22 +00:00
this.all = difference(this.all, arrayify(songs))
2022-04-15 14:24:30 +00:00
},
clear (): void {
this.all = []
},
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?
songs.forEach(song => { song.liked = true })
this.add(songs)
2022-04-24 08:50:45 +00:00
await httpService.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-04-15 14:24:30 +00:00
songs.forEach(song => { song.liked = false })
this.remove(songs)
2022-04-24 08:50:45 +00:00
await httpService.post('interaction/batch/unlike', { songs: songs.map(song => song.id) })
2022-04-15 14:24:30 +00:00
}
}