-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.ts
329 lines (291 loc) · 8.25 KB
/
client.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
type SearchParam =
| string
| number
| boolean
| string[]
| number[]
| boolean[]
| undefined;
type SearchParams = Record<string, SearchParam>;
/**
* @see https://developer.spotify.com/documentation/web-api/concepts/api-calls#regular-error-object
*/
export interface RegularErrorObject {
error: {
message: string;
status: number;
reason?: string;
};
}
const isRegularErrorObject = (
obj: unknown,
): obj is RegularErrorObject => {
if (typeof obj !== "object" || obj === null) return false;
const error = (obj as RegularErrorObject).error;
if (typeof error !== "object" || error === null) return false;
return (
typeof error.message === "string" &&
typeof error.status === "number" &&
(error.reason === undefined || typeof error.reason === "string")
);
};
export class SpotifyError extends Error {
name = "SpotifyError";
constructor(
message: string,
public readonly response: Response,
public readonly body: RegularErrorObject | string,
options?: ErrorOptions,
) {
super(message, options);
}
/**
* Shorthand for `error.response.status`
*/
get status(): number {
return this.response.status;
}
}
const getBodyMessage = (
body: RegularErrorObject | string,
): string => {
if (typeof body === "string") return body;
return body.error.message +
(body.error.reason ? ` (${body.error.reason})` : "");
};
export async function createSpotifyError(
response: Response,
options?: ErrorOptions,
): Promise<SpotifyError> {
let message = response.statusText
? `${response.status} ${response.statusText}`
: response.status.toString();
const urlWithoutQuery = response.url.split("?")[0];
if (urlWithoutQuery) {
message += ` (${urlWithoutQuery})`;
}
let body: RegularErrorObject | string = "";
if (response.body && response.type !== "opaque") {
const _body = await response.text().catch(() => null);
if (_body) {
try {
const json = JSON.parse(_body);
if (isRegularErrorObject(json)) {
body = json;
}
} catch (_) {
body = _body;
}
}
const bodyMessage = getBodyMessage(body);
if (bodyMessage) {
message += " : " + bodyMessage;
}
}
return new SpotifyError(message, response, body, options);
}
export interface FetchLikeOptions extends Omit<RequestInit, "body"> {
query?: SearchParams;
body?: BodyInit | null | Record<string, unknown> | unknown[];
}
interface MiddlewareOptions extends Omit<RequestInit, "headers"> {
query?: SearchParams;
headers: Headers;
}
type NextMiddleware = (
url: URL,
options: MiddlewareOptions,
) => Promise<Response>;
export type Middleware = (next: NextMiddleware) => NextMiddleware;
/**
* Interface for making HTTP requests to the Spotify API.
* All Soundify endpoint functions expect the client to implement this interface.
* You can create a custom client by implementing this interface.
*/
export interface HTTPClient {
fetch: (path: string, options?: FetchLikeOptions) => Promise<Response>;
}
const isPlainObject = (obj: unknown): obj is Record<PropertyKey, unknown> => {
return (
typeof obj === "object" &&
obj !== null &&
Object.prototype.toString.call(obj) === "[object Object]"
);
};
export interface SpotifyClinetOptions {
/**
* Use this option to provide a custom fetch function.
*/
fetch?: (input: URL, init?: RequestInit) => Promise<Response>;
/**
* @default "https://api.spotify.com/"
*/
baseUrl?: string;
/**
* Function that will be called when the access token is expired.
* @returns New access token.
*/
refresher?: () => Promise<string>;
/**
* Weather to wait for rate limit or not. \
* Function can be used to decide dynamically based on the `retryAfter` time in seconds.
* ```ts
* {
* waitForRateLimit: (retryAfter) => retryAfter < 10,
* }
* ```
* **Be aware that this can cause a long delay in the response.**
*
* @default false
*/
waitForRateLimit?:
| boolean
| ((retryAfter: number) => boolean);
/**
* @example
* ```ts
* const middleware: Middleware = (next) => (url, options) => {
* options.headers.set("X-Custom-Header", "custom-value");
* return next(url, options);
* }
*
* const client = new SpotifyClient("YOUR_ACCESS_TOKEN", {
* middlewares: [middleware]
* });
* ```
*/
middlewares?: Middleware[];
}
const createFailedToAuthorizeError = () =>
new Error(
"[SpotifyClient] accessToken or refresher is required to make requests.",
);
const APP_JSON = "application/json";
/**
* The main class that provides fetch method for making requests with build-in functionality for token refreshing, error handling and more.
*
* @example
* ```ts
* import { SpotifyClient } from "@soundify/web-api";
*
* // with access token
* const client = new SpotifyClient("YOUR_ACCESS_TOKEN");
*
* // with automatic token refreshing
* const client = new SpotifyClient(null, {
* // your custom refresher here
* refresher: () => Promise.resolve("NEW_ACCESS_TOKEN"),
* });
*
* // with custom options
* const client = new SpotifyClient("YOUR_ACCESS_TOKEN", {
* waitForRateLimit: true,
* middlewares: [(next) => (url, options) => {
* options.headers.set("X-Custom-Header", "custom-value");
* return next(url, options);
* }],
* })
*
* const res = await client.fetch("/v1/me");
* const user = await res.json();
* ```
*/
export class SpotifyClient implements HTTPClient {
private readonly baseUrl: string;
private refreshInProgress: Promise<void> | null = null;
constructor(accessToken: string, options?: SpotifyClinetOptions);
constructor(
accessToken: string | null,
options:
& SpotifyClinetOptions
& Required<Pick<SpotifyClinetOptions, "refresher">>,
);
constructor(
private accessToken: string | null,
private readonly options: SpotifyClinetOptions = {},
) {
if (!accessToken && !options.refresher) {
throw createFailedToAuthorizeError();
}
this.baseUrl = options.baseUrl
? options.baseUrl
: "https://api.spotify.com/";
}
fetch(path: string, opts: FetchLikeOptions = {}): Promise<Response> {
const url = new URL(path, this.baseUrl);
if (opts.query) {
for (const key in opts.query) {
const value = opts.query[key];
if (value !== undefined) {
url.searchParams.set(key, value.toString());
}
}
}
const headers = new Headers(opts.headers);
headers.set("Accept", APP_JSON);
const isBodyJSON = !!opts.body &&
(isPlainObject(opts.body) || Array.isArray(opts.body));
if (isBodyJSON) {
headers.set("Content-Type", APP_JSON);
}
const body = isBodyJSON
? JSON.stringify(opts.body)
: (opts.body as BodyInit | null | undefined);
const wrappedFetch = (this.options.middlewares || []).reduceRight(
(next, mw) => mw(next),
(this.options.fetch || globalThis.fetch) as NextMiddleware,
);
let isRefreshed = false;
if (!this.accessToken && !this.options.refresher) {
throw createFailedToAuthorizeError();
}
const getRefreshPromise = () => {
if (!this.options.refresher) return null;
if (this.refreshInProgress === null) {
this.refreshInProgress = new Promise((res, rej) => {
this.options.refresher!()
.then((newAccessToken) => {
this.accessToken = newAccessToken;
res();
})
.catch(rej)
.finally(() => this.refreshInProgress = null);
});
}
return this.refreshInProgress;
};
const recursiveFetch = async (): Promise<Response> => {
if (!this.accessToken && !isRefreshed) {
await getRefreshPromise();
isRefreshed = true;
}
headers.set("Authorization", "Bearer " + this.accessToken);
const res = await wrappedFetch(url, { ...opts, body, headers });
if (res.ok) return res;
if (res.status === 401 && this.options.refresher && !isRefreshed) {
await getRefreshPromise();
isRefreshed = true;
return recursiveFetch();
}
if (res.status === 429) {
// time in seconds
const value = res.headers.get("Retry-After");
const retryAfter = value ? parseInt(value) || undefined : undefined;
if (retryAfter) {
const waitForRateLimit =
typeof this.options.waitForRateLimit === "function"
? this.options.waitForRateLimit(retryAfter)
: this.options.waitForRateLimit;
if (waitForRateLimit) {
await new Promise((resolve) =>
setTimeout(resolve, retryAfter * 1000)
);
return recursiveFetch();
}
}
}
throw await createSpotifyError(res);
};
return recursiveFetch();
}
}