Skip to content

Instantly share code, notes, and snippets.

@imjakechapman
Created November 6, 2019 07:39
Show Gist options
  • Save imjakechapman/b754e94341f8c46bc09ddaf11bee394f to your computer and use it in GitHub Desktop.
Save imjakechapman/b754e94341f8c46bc09ddaf11bee394f to your computer and use it in GitHub Desktop.
./datasources/lastfm
import { RequestOptions, RESTDataSource } from "apollo-datasource-rest";
import { ApolloError, AuthenticationError } from "apollo-server";
// Local Types
export type IResourceTypes = "album" | "artist" | "track" | "user";
export type IMethodTypes =
| "getInfo"
| "getTags"
| "search"
| "getSimilar"
| "getTopTags"
| "getTopAlbums"
| "getTopArtists"
| "getTopTracks"
| "getLovedTracks"
| "getRecentTracks"
| "getFriends";
export interface ILastFMOptions {
resource: IResourceTypes;
method: IMethodTypes;
[key: string]: any;
}
/**
* LastFM
*/
class LastFM extends RESTDataSource {
constructor() {
super();
this.baseURL = "http://ws.audioscrobbler.com/2.0";
}
public willSendRequest(request: RequestOptions) {
if (!process.env.LASTFM_API_KEY) {
throw new AuthenticationError(
"Must configure a valid Last.fm API_KEY in your environment variables."
);
}
request.params.set("api_key", process.env.LASTFM_API_KEY);
request.params.set("format", "json");
}
public async call({ resource, method, ...options }: ILastFMOptions) {
const query = Object.keys(options)
.reduce(
(querystring: string[], key: string): string[] => {
querystring.push(`${key}=${options[key]}`);
return querystring;
},
[`method=${resource}.${method}`]
)
.join("&");
try {
return this.get("", query);
} catch (err) {
throw new ApolloError(err);
}
}
}
export { LastFM };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment