···1-import getAccessCode from "./access";
2-import { SpotifyError } from "./errors";
3-import { isNowPlaying, type nowPlaying } from "./types";
4-import { isObj, throws } from "/utils";
5-6-/**
7- * Wrapper for authorizing a spotify API with default headers etc
8- * @param url API endpoint to call. Pass a leading slash
9- * @returns `Response`
10- * @throws `SpotifyError<NETWORK_ERR>` when a fetch request fails
11- * @throws `SpotifyError<NO_AUTH>` when auth fails
12- * @throws `Response` on non 200-299 status codes
13- */
14-export async function getSpotifyApi(url: string) {
15- // get the access code
16- const accessToken = await getAccessCode();
17- // check its valid
18- if (!accessToken)
19- throw new SpotifyError(
20- "NO_AUTH",
21- null,
22- "Failed to get access code. try using src/pages/_callback",
23- );
24-25- if (accessToken instanceof SpotifyError) throw accessToken;
26-27- // fetch the api and throw on non 2** code
28- return fetch(`https://api.spotify.com/v1${url}`, {
29- headers: {
30- Authorization: `Bearer ${accessToken}`,
31- },
32- })
33- .catch((err) =>
34- err instanceof TypeError
35- ? throws(
36- new SpotifyError("NETWORK_ERR", err, "Spotify API request failed"),
37- )
38- : throws(err),
39- )
40- .then((res) => (res.ok ? res : throws(res)));
41-}
42-/**
43- * Get the current playing track
44- * @returns `nowPlaying`
45- * @throws `SpotifyError` of NO_AUTH | UNHANDLED_API_ERR | INVALID_AUTH_RES | RATE_LIMITED | NO_CONTENT | MALFORMED_SPOTIFY_RES | NETWORK_ERR
46- */
47-export async function spotifyNowPlaying() {
48- type success = nowPlaying;
49- let res: (v: success) => void, rej: (v: unknown) => void;
50- const output = new Promise<success>((_res, _rej) => {
51- ((res = _res), (rej = _rej));
52- });
53- const nowPlaying = getSpotifyApi("/me/player/currently-playing");
54-55- // auth failed
56- nowPlaying.catch((err) => {
57- if (err instanceof SpotifyError && err.code === "NO_AUTH") {
58- console.error("api.ts", "Authentication failed:", err.human);
59- rej(err);
60- } else if (err instanceof SpotifyError && err.code === "NETWORK_ERR") {
61- console.error("api.ts", "Network request failed:", err.human);
62- rej(err)
63- }
64- });
65-66- /**
67- * request failed.
68- * https://developer.spotify.com/documentation/web-api/concepts/api-calls
69- * 400 Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information; see Response Schema.
70- * 401 Unauthorized - The request requires user authentication or, if the request included authorization credentials, authorization has been refused for those credentials.
71- * 403 Forbidden - The server understood the request, but is refusing to fulfill it.
72- * 404 Not Found - The requested resource could not be found. This error can be due to a temporary or permanent condition.
73- * 429 Too Many Requests - Rate limiting has been applied.
74- * 500 Internal Server Error. You should never receive this error because our clever coders catch them all ... but if you are unlucky enough to get one, please report it to us through a comment at the bottom of this page.
75- * 502 Bad Gateway - The server was acting as a gateway or proxy and received an invalid response from the upstream server.
76- * 503 Service Unavailable - The server is currently unable to handle the request due to a temporary condition which will be alleviated after some delay. You can choose to resend the request again.
77- */
78- nowPlaying.catch((res) => {
79- switch (res.status) {
80- // handle req error
81- case 400: {
82- rej(new SpotifyError("UNHANDLED_API_ERR", res, "400: Bad request"));
83- break;
84- }
85- case 401: {
86- rej(new SpotifyError("INVALID_AUTH_RES", res, "401: Unauthorized"));
87- break;
88- }
89- case 403: {
90- rej(new SpotifyError("UNHANDLED_API_ERR", res, "403: Forbidden"));
91- break;
92- }
93- case 404: {
94- rej(new SpotifyError("UNHANDLED_API_ERR", res, "404: Not found"));
95- break;
96- }
97- case 429: {
98- rej(new SpotifyError("RATE_LIMITED", res, "429: Rate Limited"));
99- break;
100- }
101- case 500: {
102- rej(new SpotifyError("UNHANDLED_API_ERR", res, "500: Internal Error"));
103- break;
104- }
105- case 502: {
106- rej(new SpotifyError("UNHANDLED_API_ERR", res, "502: Bad Gateway"));
107- break;
108- }
109- case 503: {
110- rej(
111- new SpotifyError(
112- "UNHANDLED_API_ERR",
113- res,
114- "503: Service Unavaliable",
115- ),
116- );
117- break;
118- }
119- }
120- });
121-122- /**
123- * request succeeded
124- * https://developer.spotify.com/documentation/web-api/concepts/api-calls
125- * 200 OK - The request has succeeded. The client can read the result of the request in the body and the headers of the response.
126- * 201 Created - The request has been fulfilled and resulted in a new resource being created.
127- * 202 Accepted - The request has been accepted for processing, but the processing has not been completed.
128- * 204 No Content - The request has succeeded but returns no message body.
129- */
130- nowPlaying
131- .then((res) => {
132- if (res instanceof Error) return;
133- switch (res.status) {
134- // handle 200 codes
135- case 200: {
136- return res;
137- }
138- case 201: {
139- rej(new SpotifyError("UNHANDLED_API_ERR", res, "201: Created"));
140- return;
141- }
142- case 202: {
143- rej(new SpotifyError("UNHANDLED_API_ERR", res, "202: Accepted"));
144- return;
145- }
146- case 204: {
147- rej(new SpotifyError("NO_CONTENT", res, "204: No Content"));
148- return;
149- }
150- }
151- })
152- .then(async (resp) => {
153- // quit early if it rejected last time
154- if (!resp) return;
155- try {
156- const json = await resp
157- .json()
158- .then((res) =>
159- isObj(res) && "item" in res && isObj(res.item)
160- ? res.item
161- : throws("Item field missing"),
162- );
163-164- // verify structure
165- if (!isNowPlaying(json)) {
166- rej(
167- new SpotifyError(
168- "MALFORMED_SPOTIFY_RES",
169- json,
170- "Response missing required fields.",
171- ),
172- );
173- return;
174- }
175-176- res(json);
177- } catch (e) {
178- rej(
179- new SpotifyError("MALFORMED_SPOTIFY_RES", e, "Could not parse JSON."),
180- );
181- }
182- });
183-184- return output;
185-}