-
Notifications
You must be signed in to change notification settings - Fork 22
/
likes.ts
58 lines (49 loc) · 1.8 KB
/
likes.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
import { AxiosInstance } from 'axios'
import { TrackInfo } from './info'
import { appendURL, kindMismatchError, PaginatedQuery } from './util'
const baseURL = 'https://api-v2.soundcloud.com/users/'
export interface Like {
// eslint-disable-next-line camelcase
created_at: string,
kind: string,
track: TrackInfo
}
export interface GetLikesOptions {
profileUrl?: string
id?: number
limit?: number
offset?: number
nextHref?: string
}
/** @internal */
export const getLikes = async (options: GetLikesOptions, clientID: string, axiosInstance: AxiosInstance): Promise<PaginatedQuery<Like>> => {
// limit = limit + 1 // For some reason SoundCloud returns limit - 1, but only for likes??
let u = ''
if (!options.nextHref) {
if (!options.limit) options.limit = 10
if (!options.offset) options.offset = 0
u = appendURL(`https://api-v2.soundcloud.com/users/${options.id}/likes`, 'client_id', clientID, 'limit', '' + options.limit, 'offset', '' + options.offset)
} else {
u = appendURL(options.nextHref, 'client_id', clientID)
}
let response: PaginatedQuery<Like>
let nextHref = 'start'
while (nextHref) {
const { data } = await axiosInstance.get(u)
const query = data as PaginatedQuery<Like>
if (!query.collection) throw new Error('Invalid JSON response received')
if (query.collection.length === 0) return data
if (query.collection[0].kind !== 'like') throw kindMismatchError('like', query.collection[0].kind)
if (!response) {
response = query
} else {
response.collection.push(
// Only push tracks (for now)
...query.collection.reduce((prev, curr) => curr.track ? prev.concat(curr) : prev, [])
)
}
nextHref = query.next_href
if (nextHref) u = appendURL(nextHref, 'client_id', clientID)
}
return response
}