UNPKG

@sports-sdk/fantasypros

Version:

A package for interacting with the FantasyPros API

75 lines (71 loc) 2.59 kB
'use strict'; var core = require('@sports-sdk/core'); // src/client.ts var FantasyProsClient = class extends core.SportsSdkClient { /** * Create a FantasyPros API client * @param league - The league to get data from * @param apiKey - The API key for authenticating API requests. If not provided, it will look for `FANTASY_PROS_KEY` in the environment variables. * @throws Will throw an error if the API key is not provided or found in the environment variables. */ constructor(league, apiKey) { super("https://api.fantasypros.com/v2/json"); this.league = league; const key = apiKey || process.env.FANTASY_PROS_KEY; if (!key) { throw new Error("FantasyPros API key is required. Provide it as a parameter or set the environment variable FANTASY_PROS_KEY."); } this.session.defaults.headers.common["x-api-key"] = key; this.apiKey = key; } apiKey; isMlb() { return this.league === core.League.MLB; } isNfl() { return this.league === core.League.NFL; } /** * Sends a GET request to the specified URL path. * @param path - The path to append to base URL to send the request to. * @param additionalParams - Additional query parameters for the request. * @returns The response data from the API * @throws Will throw an error if the request fails. */ async request({ path, additionalParams = {} }) { const response = await this.session.get(path, { params: additionalParams }); if (response.status === 200) { return response.data; } throw new Error(`Failed to get a valid response: status code ${response.status}, response body ${response.data}`); } /** * Lookup the current state for the sport. The state consists of the current week in the league, season start date, current season, current week, etc. * @returns The current state of the sport. */ async getRankings(params) { const { season, position = this.isNfl() ? "OP" : "ALL", rankingsType, showExperts, specificExperts, week } = params; const additionalParams = { position, ...rankingsType && { type: rankingsType }, ...showExperts && { experts: "show" }, ...specificExperts?.length && { filters: specificExperts.join(":") }, ...week && { week }, ...!this.isMlb() && params.scoring && { scoring: params.scoring } }; return await this.request({ path: `/${this.league.toLowerCase()}/${season}/consensus-rankings`, additionalParams }); } }; exports.FantasyProsClient = FantasyProsClient;