fpl-fetch
Version:
Wrapper for the Fantasy Premier League API
340 lines (336 loc) • 9.26 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/index.ts
var index_exports = {};
__export(index_exports, {
default: () => FplFetch
});
module.exports = __toCommonJS(index_exports);
// src/client/index.ts
var APIError = class extends Error {
/**
* Creates a new APIError instance
* @param code - HTTP status code of the error
* @param message - Error message
* @param originalError - Optional original error that caused this error
*/
constructor(code, message, originalError) {
super(message);
this.code = code;
this.originalError = originalError;
}
};
var Client = class {
/**
* Creates a new API client instance
* @param debug - Optional flag to enable debug logging
*/
constructor(debug) {
this.baseUrl = "https://fantasy.premierleague.com/api";
this.debug = false;
this.success = false;
this.status = 500;
this.debug = debug != null ? debug : false;
}
/**
* Logs debug information about an API request
* @param resource - The API resource path that was requested
* @param status - The HTTP status code returned from the request
* @param duration - The duration of the request in milliseconds
* @param success - Whether the request was successful
* @returns void
*/
logDebug(resource, status, duration, success) {
if (!this.debug) return;
console.debug(
`[DEBUG] ${(/* @__PURE__ */ new Date()).toISOString()} GET ${resource} | Status: ${status} | Duration ${duration}ms`,
{
baseUrl: this.baseUrl,
debug: this.debug,
resource,
success
}
);
}
/**
* Makes a GET request to the Fantasy Premier League API
* @param resource - The API resource path to request (e.g. "bootstrap-static/")
* @returns Promise that resolves with the typed response data
* @throws {@link APIError} If the request fails with a non-200 status code
* @throws {@link APIError} If there is a network or parsing error (with 500 status)
* @example
* const data = await client.get<BootstrapResponse>("bootstrap-static/");
*/
get(resource) {
return __async(this, null, function* () {
const start = this.debug ? performance.now() : 0;
try {
const result = yield fetch(`${this.baseUrl}/${resource}`);
if (!result.ok) {
throw new APIError(result.status, result.statusText);
}
const data = yield result.json();
this.success = true;
this.status = result.status;
return data;
} catch (error) {
if (error instanceof APIError) {
this.success = false;
this.status = error.code;
throw error;
} else {
throw new APIError(500, "Third-party API failed", error);
}
} finally {
if (this.debug) {
this.logDebug(
resource,
this.status,
performance.now() - start,
this.success
);
}
}
});
}
};
// src/index.ts
var endpoints = {
bootstrap: "bootstrap-static/",
eventStatus: "event-status/",
fixtures: "fixtures/",
gameweek: (id) => `event/${id}/live/`,
player: (id) => `element-summary/${id}/`,
manager: (id) => `entry/${id}/`,
managerTransfers: (id) => `entry/${id}/transfers/`,
managerHistory: (id) => `entry/${id}/history/`,
managerGameweekPicks: (id, gameweekId) => `entry/${id}/event/${gameweekId}/picks/`
};
var FplFetch = class {
/**
* Creates a new FPL API client
* @param config - Configuration options
*
* @example
* ```ts
* const fpl = new FplFetch({ debug: true });
* ```
*/
constructor(config) {
this.config = {
debug: false
};
if (config) {
this.config = config;
}
this.client = new Client(this.config.debug);
}
/**
* Retrieves the bootstrap static data from the FPL API.
* This data contains core information about the current FPL season including:
* teams, players, game settings and rules.
* @returns Bootstrap data
*
* @example
* ```ts
* try {
* const data = await fpl.getBootstrapData();
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getBootstrapData() {
return __async(this, null, function* () {
return this.client.get(endpoints.bootstrap);
});
}
/**
* Gets the current event status.
* This provides information about the current gameweek, and whether bonus points have been added.
* @returns Current event status data
*
* @example
* ```ts
* try {
* const data = await fpl.getCurrentEvent();
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getCurrentEvent() {
return __async(this, null, function* () {
return this.client.get(endpoints.eventStatus);
});
}
/**
* Gets all fixtures for the current season.
* @returns List of fixtures
*
* @example
* ```ts
* try {
* const data = await fpl.getFixtures();
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getFixtures() {
return __async(this, null, function* () {
return this.client.get(endpoints.fixtures);
});
}
/**
* Gets live data for a specific gameweek
* @param id - Gameweek ID
* @returns Live gameweek data
*
* @example
* ```ts
* try {
* const data = await fpl.getGameweek(1);
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getGameweek(id) {
return __async(this, null, function* () {
return this.client.get(endpoints.gameweek(id));
});
}
/**
* Gets detailed data for a specific player
* @param id - Player ID
* @returns Player summary data
*
* @example
* ```ts
* try {
* const data = await fpl.getPlayer(1);
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getPlayer(id) {
return __async(this, null, function* () {
return this.client.get(endpoints.player(id));
});
}
/**
* Gets detailed data for a specific manager
* @param id - Manager ID
* @returns Manager summary data
*
* @example
* ```ts
* try {
* const data = await fpl.getManager(1);
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getManager(id) {
return __async(this, null, function* () {
return this.client.get(endpoints.manager(id));
});
}
/**
* Gets transfer history for a specific manager
* @param id - Manager ID
* @returns List of transfers made by the manager
*
* @example
* ```ts
* try {
* const data = await fpl.getManagerTransfers(1);
* } catch (error: unknown) {
* console.error(error);
* }}
* ```
*/
getManagerTransfers(id) {
return __async(this, null, function* () {
return this.client.get(endpoints.managerTransfers(id));
});
}
/**
* Gets historical data for a specific manager
* @param id - Manager ID
* @returns Manager history data including past seasons and current season performance
*
* @example
* ```ts
* try {
* const data = await fpl.getManagerHistory(1);
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getManagerHistory(id) {
return __async(this, null, function* () {
return this.client.get(endpoints.managerHistory(id));
});
}
/**
* Gets a manager's team picks for a specific gameweek
* @param id - Manager ID
* @param gameweekId - Gameweek ID
* @returns Manager's team selection and points for the specified gameweek
*
* @example
* ```ts
* try {
* const data = await fpl.getManagerGameweekPicks(1, 1);
* } catch (error: unknown) {
* console.error(error);
* }
* ```
*/
getManagerGameweekPicks(id, gameweekId) {
return __async(this, null, function* () {
return this.client.get(endpoints.managerGameweekPicks(id, gameweekId));
});
}
};