Skip to content

Commit

Permalink
refactor: 🚚 small reorganisation of functions
Browse files Browse the repository at this point in the history
  • Loading branch information
josephshambrook committed Nov 20, 2022
1 parent f8dd7bd commit 0455950
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 15 deletions.
26 changes: 11 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getAccessToken } from "./lib/spotify";
import { Router } from "itty-router";
import { mapTracks } from "./lib/mapping";
import { getAccessToken, getTopTracks } from "./lib/spotify";
import { mapTracks } from "./lib/utils";

const router = Router();

Expand All @@ -22,23 +22,19 @@ router.get("/top", async (request, env, context) => {

const url = new URL(request.url);

// all search parameter options
const type = url.searchParams.get("type") ?? "tracks";
const time_range = url.searchParams.get("time_range") ?? "short_term";
const timeRange = url.searchParams.get("time_range") ?? "short_term";
const limit = url.searchParams.get("limit") ?? "20";
const offset = url.searchParams.get("offset") ?? "0";

const rawResponse: SpotifyApi.UsersTopTracksResponse = await fetch(
`https://api.spotify.com/v1/me/top/${type}?time_range=${time_range}&limit=${limit}&offset=${offset}`,
{
cf: {
cacheTtl: 3600,
cacheEverything: true,
},
headers: {
Authorization: `Bearer ${access_token}`,
},
}
).then((r) => r.json());
const rawResponse = await getTopTracks({
accessToken: access_token,
type,
timeRange,
limit,
offset,
});

const mappedResponse = mapTracks(rawResponse.items);

Expand Down
29 changes: 29 additions & 0 deletions src/lib/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,32 @@ export const getAccessToken = ({
return r as SpotifyAccessTokenResponse;
});
};

type getTopTracksParams = {
accessToken: string;
type: string;
timeRange: string;
limit: string;
offset: string;
};

export const getTopTracks = ({
accessToken,
type,
timeRange,
limit,
offset,
}: getTopTracksParams): Promise<SpotifyApi.UsersTopTracksResponse> => {
return fetch(
`https://api.spotify.com/v1/me/top/${type}?time_range=${timeRange}&limit=${limit}&offset=${offset}`,
{
cf: {
cacheTtl: 3600,
cacheEverything: true,
},
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
).then((r) => r.json());
};
File renamed without changes.

0 comments on commit 0455950

Please sign in to comment.