Skip to content
This repository has been archived by the owner on Jun 1, 2024. It is now read-only.

Commit

Permalink
fix: refresh access token if it is expired
Browse files Browse the repository at this point in the history
  • Loading branch information
skick1234 committed Sep 4, 2022
1 parent e3139ff commit bc63550
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
15 changes: 10 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,21 @@ declare type SpotifyPluginOptions = {
type Falsy = undefined | null | false | 0 | "";
const isTruthy = <T>(x: T | Falsy): x is T => Boolean(x);

const refreshAPIToken = async () => {
if (expirationTime <= Date.now() - 60000) {
const res = await API.refreshAccessToken().catch(() => API.clientCredentialsGrant());
expirationTime = Date.now() + res.body.expires_in * 1000;
API.setAccessToken(res.body.access_token);
}
};

const getItems = async (data: any): Promise<any[]> => {
if (!data.tracks.items) return data.tracks;
const items: any[] = data.tracks.items;
if (!["playlist", "album"].includes(data.type)) return items;
while (data.tracks.next) {
if (!expirationTime) break;
if (expirationTime <= Date.now() - 60000) {
const res = await API.refreshAccessToken().catch(() => API.clientCredentialsGrant());
expirationTime = Date.now() + res.body.expires_in * 1000;
API.setAccessToken(res.body.access_token);
}
await refreshAPIToken();
try {
data.tracks = (
await API[data.type === "playlist" ? "getPlaylistTracks" : "getAlbumTracks"](data.id, {
Expand All @@ -58,6 +62,7 @@ const getDataWithAPI = async (url: string) => {
let data: any;
const id = (<any>parsedURL).id;
if (!id) throw new DisTubeError("SPOTIFY_PLUGIN_UNSUPPORTED_LINK", "This link is not supported.");
await refreshAPIToken();
try {
switch (parsedURL.type) {
case "track":
Expand Down
2 changes: 1 addition & 1 deletion tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const tsup: Options = {
clean: true,
dts: true,
entry: ["src/index.ts"],
format: ["esm", "cjs"],
format: "cjs",
minify: false,
keepNames: true,
skipNodeModulesBundle: true,
Expand Down

0 comments on commit bc63550

Please sign in to comment.