typerinth
Version:
A TypeScript library for interacting with the Modrinth API.
98 lines (97 loc) • 2.85 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Route = void 0;
class Route {
/**
* The base URL for the API (e.g. https://api.modrinth.com/v2)
* @protected
*/
baseUrl;
/**
* The user agent to use for the request
* @protected
*/
ua;
/**
* The authorization token to use for the request
* @protected
*/
authorization;
/**
* The cache options for the route
*/
cacheManager;
/**
* Create a new Route instance
* @param baseUrl - The base URL for the API
* @param ua - The user agent to use for the request
* @param cacheManager - The cache manager to use for the route
* @param authorization - The authorization token to use for the request
*/
constructor(baseUrl, ua, cacheManager, authorization) {
this.baseUrl = baseUrl;
this.ua = ua;
this.cacheManager = cacheManager;
this.authorization = authorization;
}
/**
* Get the fetch method for the request
* @returns The fetch method to use for the request
* @protected
*/
getFetchMethod() {
return 'GET';
}
/**
* Get the body for the fetch request
* @returns The body for the fetch request
* @protected
*/
getFetchBody() {
return null;
}
/**
* Fetch the raw data from the url
* @returns The data from the API
*/
async fetchRaw() {
return fetch(this.getUrl().toString(), {
method: this.getFetchMethod(),
headers: {
'User-Agent': this.ua ?? '',
Authorization: this.authorization ?? '',
'Content-Type': this.getFetchBody()?.getContentType() ?? '',
},
body: this.getFetchBody()?.getFormattedBody() ?? undefined,
});
}
/**
* Get the data from the API
* @returns The data from the API
*/
async getData() {
if (this.cacheManager.isEnabled() && this.getCacheKey() != null) {
const cachedData = this.cacheManager.get(this.getCacheKey());
if (cachedData) {
return cachedData;
}
}
const res = await this.fetchRaw();
let rawData = null;
try {
rawData = await res.json();
}
catch (error) {
rawData = null;
}
const parsedData = this.parseData(rawData, res.status);
if (this.cacheManager.isEnabled() && this.getCacheKey() != null)
this.cacheManager.set(this.getCacheKey(), parsedData);
return parsedData;
}
static addPathSegment(url, pathSegment) {
url.pathname = `${url.pathname.replace(/\/$/, '')}/${pathSegment.replace(/^\//, '')}`;
return url;
}
}
exports.Route = Route;