igdb-ts
Version:
Unofficial IGDB API TypeScript wrapper.
635 lines • 23.5 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IGDB = void 0;
const axios_1 = __importDefault(require("axios"));
const axios_rate_limit_1 = __importDefault(require("axios-rate-limit"));
const types_1 = require("./types");
class IGDB {
/**
* Use function init() before calling endpoints.
*/
constructor() {
this.API_URL = "https://api.igdb.com/v4";
this.IMAGE_URL = "https://images.igdb.com/igdb/image/upload";
this._axios = (0, axios_rate_limit_1.default)(axios_1.default.create(), { maxRPS: 4, perMilliseconds: 1000, maxRequests: 4 });
}
/**
* Initialises wrapper and generates access token (if needed) to call API.
* @param clientId - Twitch Client Id
* @param clientSecret - Twitch Client Secret
* @param clientToken - Twitch App Access Token
* @param rateLimitOptions - Axios Rate Limit Options. Default is 4 requests/s as per IGDB documentation.
* @param onAccessTokenRetrieved - Callback which can be used to save token to storage. Includes timestamp of when the token will expire.
*/
init(clientId, clientSecret, clientToken, onAccessTokenRetrieved, rateLimitOptions) {
return __awaiter(this, void 0, void 0, function* () {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.onAccessTokenRetrieved = onAccessTokenRetrieved;
if (!clientToken) {
yield this.getToken();
}
else {
this.clientToken = clientToken.token;
this.tokenExpiry = clientToken.tokenExpiry;
}
if (rateLimitOptions) {
this._axios.setRateLimitOptions(rateLimitOptions);
}
});
}
/**
* Ensures token is valid and has not expired.
*/
validateToken() {
return __awaiter(this, void 0, void 0, function* () {
let currentTime = new Date().getTime();
if (currentTime >= this.tokenExpiry) {
yield this.getToken();
}
});
}
/**
* Can be used to generate a new access token.
*
* As per documentation, the access token cannot be refreshed. Therefore, when an access token expires you need create a new one.
*
* https://dev.twitch.tv/docs/authentication/refresh-tokens
*/
getToken() {
return __awaiter(this, void 0, void 0, function* () {
let response = yield axios_1.default.post(`https://id.twitch.tv/oauth2/token?client_id=${this.clientId}&client_secret=${this.clientSecret}&grant_type=client_credentials`)
.then((response) => {
if (response.data) {
return response.data;
}
});
//expires_in is expressed in seconds not milliseconds therefore, *1000
const expiry = new Date().getTime() + (response.expires_in * 1000);
this.clientToken = response.access_token;
this.tokenExpiry = expiry;
this.onAccessTokenRetrieved(response.access_token, expiry);
});
}
buildFilter({ filters, operators }) {
//For every 2, filters there must be 1 operator 8 querys = 4 operators
if (filters.length === 0) {
throw Error("You need to provide at least one filter.");
}
if (filters.length > 1) {
if (!operators || (operators.length != filters.length / 2)) {
throw Error("You must provide 1 operator for every two filters.");
}
}
let _filter = "";
//if 1 then add
for (let i = 0; i < filters.length; i++) {
if (i % 2 !== 0) {
_filter += ` ${operators[i - 1]} `;
}
let f = filters[i];
_filter += `${f.field} ${f.postfix} ${f.value}`;
}
return _filter;
}
buildCombinedFilter({ filters, operators }) {
if (filters.length <= 1) {
throw Error("A combined filter required at least two filters.");
}
else {
if (!operators || (operators.length != filters.length / 2)) {
throw Error("You must provide 1 operator for every two filters.");
}
}
let _combinedFilter = "";
for (let i = 0; i < filters.length; i++) {
if (i % 2 !== 0) {
_combinedFilter += ` ${operators[i - 1]} `;
}
let f = filters[i];
_combinedFilter += `(${this.buildFilter(f)})`;
}
return _combinedFilter;
}
buildOptions(options) {
//If no options, get all fields
if (!options) {
return `fields *;`;
}
let result = "";
if (options.fields) {
result += `fields ${options.fields.join(",")};`;
}
else {
result += `fields *;`;
}
if (options.exclude) {
result += `exclude ${options.exclude.join(",")};`;
}
if (options.filter) {
let filtersAsString = this.buildFilter(options.filter);
result += `where ${filtersAsString};`;
}
if (options.combinedFilter) {
let filtersAsString = this.buildCombinedFilter(options.combinedFilter);
result += `where ${filtersAsString};`;
}
if (options.sortBy) {
result += `sort ${options.sortBy.field} ${options.sortBy.order};`;
}
if (options.search) {
result += `search "${options.search}";`;
}
if (options.limit) {
result += `limit ${options.limit};`;
}
if (options.offset) {
result += `offset ${options.offset};`;
}
return result;
}
buildUntypedOptions(options) {
//If no options, get all fields
if (!options) {
return `fields *;`;
}
let result = "";
if (options.fields) {
result += `fields ${options.fields.join(",")};`;
}
else {
result += `fields *;`;
}
if (options.exclude) {
result += `exclude ${options.exclude.join(",")};`;
}
if (options.filter) {
let filtersAsString = this.buildFilter(options.filter);
result += `where ${filtersAsString};`;
}
if (options.combinedFilter) {
let filtersAsString = this.buildCombinedFilter(options.combinedFilter);
result += `filters ${filtersAsString};`;
}
if (options.sortBy) {
result += `sort ${options.sortBy.field} ${options.sortBy.order};`;
}
if (options.search) {
result += `search "${options.search}";`;
}
if (options.limit) {
result += `limit ${options.limit};`;
}
if (options.offset) {
result += `offset ${options.offset};`;
}
return result;
}
request(endpoint, options) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.clientToken) {
throw Error("Client token not found. Make sure to init() before requesting an endpoint.");
}
return this.validateToken().then(() => this._axios.post(`${this.API_URL}/${endpoint}`, this.buildOptions(options), {
headers: {
'Client-ID': this.clientId,
'Authorization': `Bearer ${this.clientToken}`,
'Accept': 'application/json',
},
}))
.then((response) => {
return response.data;
});
});
}
buildMultiQuery(queries) {
if (queries.length < 2) {
throw Error("You need at least two queries to multiquery.");
}
if (queries.length > 10) {
throw Error("You can only run a maxiumum of 10 queries.");
}
let query = "";
queries.forEach((q) => {
query += `query ${q.endpoint} "${q.resultName}" {${q.options ? this.buildUntypedOptions(q.options) : ""}};`;
});
return query;
}
/**
* Get a multiquery.
*
*
* Maximum of 10 Queries.
*
* {@link https://api-docs.igdb.com/#multi-query}
* @param {Array} queries - an array of [Query]({@link Query})
* @returns any[]
**/
multiQuery(queries) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.clientToken) {
throw Error("Client token not found. Make sure to init() before requesting an endpoint.");
}
return this.validateToken().then(() => this._axios.post(`${this.API_URL}/multiquery`, this.buildMultiQuery(queries), {
headers: {
'Client-ID': this.clientId,
'Authorization': `Bearer ${this.clientToken}`,
'Accept': 'application/json',
}
})).then((response) => {
return response.data;
});
});
}
/**
* Get an Image URL.
* {@link https://api-docs.igdb.com/#images}
* @param {Object} imageOptions - [Image Options]({@link ImageOptions})
*
**/
getImageUrl({ imageId, size, retina }) {
return `${this.IMAGE_URL}/t_${size}${retina && "_2x"}/${imageId}.jpg`;
}
/**
* Generic Endpoint Call.
*
* Provide your own endpoint and response type.
*
* {@link https://api-docs.igdb.com/#about}
* @param {Object} options - [Untyped Endpoint Options]({@link UntypedIGDBOptions})
*
**/
get(endpoint, options) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.clientToken) {
throw Error("Client token not found. Make sure to init() before requesting an endpoint.");
}
return this.validateToken().then(() => this._axios.post(`${this.API_URL}/${endpoint}`, this.buildUntypedOptions(options), {
headers: {
'Client-ID': this.clientId,
'Authorization': `Bearer ${this.clientToken}`,
'Accept': 'application/json',
},
}))
.then((response) => {
return response.data;
});
});
}
/**
* Get Age Ratings.
* {@link https://api-docs.igdb.com/#age-rating}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getAgeRatings(options) {
return this.request(types_1.Endpoints.AGE_RATING, options);
}
/**
* Get Age Rating Content Descriptions.
* {@link https://api-docs.igdb.com/#age-rating-content-description}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getAgeRatingContentDescriptions(options) {
return this.request(types_1.Endpoints.AGE_RATING_CONTENT_DESCRIPTION, options);
}
/**
* Get Alternative Names.
* {@link https://api-docs.igdb.com/#alternative-name}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getAlternativeNames(options) {
return this.request(types_1.Endpoints.ALTERNATIVE_NAME, options);
}
/**
* Get Artworks.
* {@link https://api-docs.igdb.com/#artwork}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getArtworks(options) {
return this.request(types_1.Endpoints.ARTWORK, options);
}
/**
* Get Characters.
* {@link https://api-docs.igdb.com/#character}
* @param {Object} options - [Searchable Endpoint Options]({@link SearchableIGDBOptions})
*
**/
getCharacters(options) {
return this.request(types_1.Endpoints.CHARACTER, options);
}
/**
* Get Character Mug Shot.
* {@link https://api-docs.igdb.com/#character-mug-shot}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getCharacterMugShots(options) {
return this.request(types_1.Endpoints.CHARACTER_MUG_SHOT, options);
}
/**
* Get Collections.
* {@link https://api-docs.igdb.com/#collection}
* @param {Object} options - [Searchable Endpoint Options]({@link SearchableIGDBOptions})
*
**/
getCollections(options) {
return this.request(types_1.Endpoints.COLLECTION, options);
}
/**
* Get Companies.
* {@link https://api-docs.igdb.com/#company}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getCompanies(options) {
return this.request(types_1.Endpoints.COMPANY, options);
}
/**
* Get Company Logos.
* {@link https://api-docs.igdb.com/#company-logo}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getCompanyLogos(options) {
return this.request(types_1.Endpoints.COMPANY_LOGO, options);
}
/**
* Get Company Website.
* {@link https://api-docs.igdb.com/#company-website}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getCompanyWebsite(options) {
return this.request(types_1.Endpoints.COMPANY_WEBSITE, options);
}
/**
* Get Covers.
* {@link https://api-docs.igdb.com/#cover}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getCovers(options) {
return this.request(types_1.Endpoints.COVER, options);
}
/**
* Get External Games.
* {@link https://api-docs.igdb.com/#external-game}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getExternalGames(options) {
return this.request(types_1.Endpoints.EXTERNAL_GAME, options);
}
/**
* Get Franchises.
* {@link https://api-docs.igdb.com/#franchise}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getFranchises(options) {
return this.request(types_1.Endpoints.FRANCHISE, options);
}
/**
* Get Games.
* {@link https://api-docs.igdb.com/#game}
* @param {Object} options - [Searchable Endpoint Options]({@link SearchableIGDBOptions})
*
**/
getGames(options) {
return this.request(types_1.Endpoints.GAME, options);
}
/**
* Get Game Engines.
* {@link https://api-docs.igdb.com/#game-engine}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGameEngines(options) {
return this.request(types_1.Endpoints.GAME_ENGINE, options);
}
/**
* Get Game Engine Logos.
* {@link https://api-docs.igdb.com/#game-engine-logo}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGameEngineLogos(options) {
return this.request(types_1.Endpoints.GAME_ENGINE_LOGO, options);
}
/**
* Get Game Modes.
* {@link https://api-docs.igdb.com/#game-mode}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGameModes(options) {
return this.request(types_1.Endpoints.GAME_MODE, options);
}
/**
* Get Game Versions.
* {@link https://api-docs.igdb.com/#game-version}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGameVersions(options) {
return this.request(types_1.Endpoints.GAME_VERSION, options);
}
/**
* Get Game Version Features.
* {@link https://api-docs.igdb.com/#game-version-feature}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGameVersionFeatures(options) {
return this.request(types_1.Endpoints.GAME_VERSION_FEATURE, options);
}
/**
* Get Game Version Feature Values.
* {@link https://api-docs.igdb.com/#game-engine-feature-value}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGameVersionFeatureValues(options) {
return this.request(types_1.Endpoints.GAME_VERSION_FEATURE_VALUE, options);
}
/**
* Get Game Videos.
* {@link https://api-docs.igdb.com/#game-video}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGameVideos(options) {
return this.request(types_1.Endpoints.GAME_VIDEO, options);
}
/**
* Get Genres.
* {@link https://api-docs.igdb.com/#genre}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getGenres(options) {
return this.request(types_1.Endpoints.GENRE, options);
}
/**
* Get Involved Companies.
* {@link https://api-docs.igdb.com/#involved-company}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getInvolvedCompanies(options) {
return this.request(types_1.Endpoints.INVOLVED_COMPANY, options);
}
/**
* Get Keywords.
* {@link https://api-docs.igdb.com/#keyword}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getKeywords(options) {
return this.request(types_1.Endpoints.KEYWORD, options);
}
/**
* Get Multiplayer Modes.
* {@link https://api-docs.igdb.com/#multiplayer-mode}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getMultiplayerModes(options) {
return this.request(types_1.Endpoints.MULTIPLAYER_MODE, options);
}
/**
* Get Platform.
* {@link https://api-docs.igdb.com/#platform}
* @param {Object} options - [Searchable Endpoint Options]({@link SearchableIGDBOptions})
*
**/
getPlatforms(options) {
return this.request(types_1.Endpoints.PLATFORM, options);
}
/**
* Get Platform Families.
* {@link https://api-docs.igdb.com/#platform-family}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getPlatformFamilies(options) {
return this.request(types_1.Endpoints.PLATFORM_FAMILY, options);
}
/**
* Get Platform Logos.
* {@link https://api-docs.igdb.com/#platform-logo}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getPlatformLogos(options) {
return this.request(types_1.Endpoints.PLATFORM_LOGO, options);
}
/**
* Get Platform Versions.
* {@link https://api-docs.igdb.com/#platform-version}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getPlatformVersion(options) {
return this.request(types_1.Endpoints.PLATFORM_VERSION, options);
}
/**
* Get Platform Version Companies.
* {@link https://api-docs.igdb.com/#platform-version-company}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getPlatformVersionCompanies(options) {
return this.request(types_1.Endpoints.PLATFORM_VERSION_COMPANY, options);
}
/**
* Get Platform Version Release Dates.
* {@link https://api-docs.igdb.com/#platform-version-release_date}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getPlatformVersionReleaseDates(options) {
return this.request(types_1.Endpoints.PLATFORM_VERSION_RELEASE_DATE, options);
}
/**
* Get Platform Websites.
* {@link https://api-docs.igdb.com/#platform-website}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getPlatformWebsites(options) {
return this.request(types_1.Endpoints.PLATFORM_WEBSITE, options);
}
/**
* Get Player Perspectives.
* {@link https://api-docs.igdb.com/#player-perspective}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getPlayerPerspectives(options) {
return this.request(types_1.Endpoints.PLAYER_PERSPECTIVE, options);
}
/**
* Get Release Dates.
* {@link https://api-docs.igdb.com/#release-date}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getReleaseDates(options) {
return this.request(types_1.Endpoints.RELEASE_DATE, options);
}
/**
* Get Screenshots.
* {@link https://api-docs.igdb.com/#screenshot}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getScreenshots(options) {
return this.request(types_1.Endpoints.SCREENSHOT, options);
}
/**
* Search IGDB.
* {@link https://api-docs.igdb.com/#search}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
search(options) {
return this.request(types_1.Endpoints.SEARCH, options);
}
/**
* Get Themes.
* {@link https://api-docs.igdb.com/#theme}
* @param {Object} options - [Searchable Endpoint Options]({@link SearchableIGDBOptions})
*
**/
getThemes(options) {
return this.request(types_1.Endpoints.THEME, options);
}
/**
* Get Websites.
* {@link https://api-docs.igdb.com/#website}
* @param {Object} options - [Default Endpoint Options]({@link DefaultIGDBOptions})
*
**/
getWebsites(options) {
return this.request(types_1.Endpoints.WEBSITE, options);
}
}
exports.IGDB = IGDB;
//# sourceMappingURL=index.js.map