1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { defineStore } from 'pinia'
type MediaType = 'track' | 'album' | 'artist'
export const useFavouriteStore = defineStore('favourite', {
state: () => ({
albums: {} as any,
artists: {} as any,
tracks: {} as any,
}),
actions: {
load() {
return this.subsonicApi.getFavourites().then(result => {
this.albums = createIdMap(result.albums)
this.artists = createIdMap(result.artists)
this.tracks = createIdMap(result.tracks)
})
},
get(type: MediaType, id: string) {
console.info('favouriteStore.get(): ', id)
const field = getTypeKey(type)
return !!this[field][id]
},
toggle(type: MediaType, id: string) {
console.info('favouriteStore.toggle(): ', id)
const field = getTypeKey(type)
if (this[field][id]) {
delete this[field][id]
return this.subsonicApi.removeFavourite(id, type)
} else {
this[field][id] = true
return this.subsonicApi.addFavourite(id, type)
}
},
},
})
function createIdMap(items: [{ id: string }]) {
return Object.assign({}, ...items.map((item) => ({ [item.id]: true })))
}
function getTypeKey(type: string): 'albums' | 'artists' |'tracks' {
switch (type) {
case 'album': return 'albums'
case 'artist': return 'artists'
case 'track': return 'tracks'
default: throw new Error(`unknown favourite type '${type}'`)
}
}