-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.ts
81 lines (66 loc) · 2.06 KB
/
spotify.ts
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import SpotifyWebApi from "spotify-web-api-js";
interface Pagination {
next?: string;
items: SpotifyApi.SavedAlbumObject[];
}
export type GroupedAlbums = Map<number, SpotifyApi.AlbumObjectFull[]>;
const spotifyApi = new SpotifyWebApi();
const getAllPages = async <Response extends Pagination>(
request: Promise<Response>,
): Promise<Response> => {
const paginatedResponse = await request;
let currentResponse = paginatedResponse;
while (currentResponse.next) {
currentResponse = await spotifyApi.getGeneric(
currentResponse.next,
) as Response;
paginatedResponse.items = paginatedResponse.items.concat(
currentResponse.items,
);
}
return paginatedResponse;
};
const groupAlbumsByYear = (albums: SpotifyApi.SavedAlbumObject[]) =>
albums.reduce(
(group, { album }) => {
const releaseYear = (new Date(album.release_date)).getFullYear();
if (group.has(releaseYear)) group.get(releaseYear)!.push(album);
else group.set(releaseYear, [album]);
return group;
},
new Map(),
);
const sortGroupedAlbumsInDescendingOrder = (groupedAlbums: GroupedAlbums) =>
groupedAlbums.forEach((albums, year: number) => {
groupedAlbums.set(
year,
albums.sort(
(
left: SpotifyApi.AlbumObjectFull,
right: SpotifyApi.AlbumObjectFull,
) => {
const leftDate = new Date(left.release_date);
const rightDate = new Date(right.release_date);
if (leftDate > rightDate) {
return -1;
} else if (rightDate > leftDate) {
return 1;
}
return 0;
},
),
);
});
export default async function fetchSavedAlbums(
access_token: string,
): Promise<GroupedAlbums> {
spotifyApi.setAccessToken(access_token);
const paginatedResponse = await getAllPages<
SpotifyApi.UsersSavedAlbumsResponse
>(
spotifyApi.getMySavedAlbums({ limit: 50 }),
);
const groupedAlbums = groupAlbumsByYear(paginatedResponse.items);
sortGroupedAlbumsInDescendingOrder(groupedAlbums);
return groupedAlbums;
}