diff --git a/src/shared/base/BaseRequest.ts b/src/shared/base/BaseRequest.ts index 7f12915..dfa37dc 100644 --- a/src/shared/base/BaseRequest.ts +++ b/src/shared/base/BaseRequest.ts @@ -1,14 +1,21 @@ export default class BaseRequest { private url: string; private options: RequestInit; + private queryOptions: URLSearchParams; - constructor(url: string, options: RequestInit) { + constructor(url: string, options: RequestInit, queryOptions = {}) { this.url = url; this.options = options; + this.queryOptions = new URLSearchParams(queryOptions); } private async request(path: string, options: RequestInit): Promise { - const endpoint = `${this.url}${path.startsWith("/") ? "" : "/"}${path}`; + const dash = path.startsWith("/") ? "" : "/"; + const prefix = path.includes("?") ? "&" : "?"; + + const query = `${prefix}${this.queryOptions.toString()}`; + const endpoint = `${this.url}${dash}${path}${query}`; + const response: Response = await fetch(endpoint, { ...this.options, ...options, diff --git a/src/shared/integrations/LastFmAPI.ts b/src/shared/integrations/LastFmAPI.ts index 4a00369..4cf1bc2 100644 --- a/src/shared/integrations/LastFmAPI.ts +++ b/src/shared/integrations/LastFmAPI.ts @@ -2,16 +2,14 @@ import BaseRequest from "@/shared/base/BaseRequest.js"; import type { TopArtistsData, UserArtistData } from "../types/lastFmTypes.js"; export default class LastFmAPI extends BaseRequest { - apiKey: string; - constructor() { - super("http://ws.audioscrobbler.com/2.0/", {}); - - this.apiKey = process.env.LASTFM_APIKEY ?? ""; - } - - private applyApiKey(method: string) { - return `${method}&api_key=${this.apiKey}`; + super( + "http://ws.audioscrobbler.com/2.0", + {}, + { + api_key: process.env.LASTFM_APIKEY ?? "", + }, + ); } public async getTopArtists( @@ -20,9 +18,7 @@ export default class LastFmAPI extends BaseRequest { page: number, ): Promise { const data: TopArtistsData = await this.get( - this.applyApiKey( - `?method=user.getTopArtists&user=${username}&format=json&limit=${limit}&page=${page}`, - ), + `?method=user.getTopArtists&user=${username}&format=json&limit=${limit}&page=${page}`, ); if (!data) return null; @@ -32,9 +28,7 @@ export default class LastFmAPI extends BaseRequest { public async getTotalArtists(username: string): Promise { const data: TopArtistsData = await this.get( - this.applyApiKey( - `?method=user.getTopArtists&user=${username}&format=json&limit=1`, - ), + `?method=user.getTopArtists&user=${username}&format=json&limit=1`, ); if (!data) return null; @@ -44,11 +38,9 @@ export default class LastFmAPI extends BaseRequest { public async getArtistInfo(artistName: string): Promise { return await this.get( - this.applyApiKey( - `?method=artist.getInfo&artist=${encodeURIComponent( - artistName, - )}&format=json`, - ), + `?method=artist.getInfo&artist=${encodeURIComponent( + artistName, + )}&format=json`, ); } }