api-railway
Version:
Api wrapper for api.railwayapi.site
126 lines • 3.6 kB
JavaScript
import HealthCheck from "./health_check.js";
import Schedules from "./schedules.js";
import Stations from "./stations.js";
import Trains from "./trains.js";
import TrainsBtwStations from "./trainsBtwStations.js";
export async function catchError(promise) {
try {
const data = await promise;
return [undefined, data];
}
catch (error) {
return [error];
}
}
export async function fetchJson(input, init) {
const errorRes = await catchError(fetch(input, init));
if (errorRes[0]) {
return errorRes;
}
return await catchError(errorRes[1].json());
}
export class URLBuilder {
baseURL;
segments = [];
queryParameters;
headers;
body;
method;
constructor(baseURL, headers = {}) {
this.headers = headers;
this.baseURL = baseURL;
this.method = "GET";
this.body = null;
}
// Add resource and query parameters
addResource(resource) {
this.segments.push(resource);
return this;
}
addQueryParam(value) {
this.queryParameters = value;
return this;
}
addHeader(key, value) {
this.headers[key] = value;
return this;
}
setBody(body) {
this.body = body;
return this;
}
setMethod(method) {
this.method = method;
return this;
}
// Build the URL
buildURL() {
let url = `${this.baseURL}/${this.segments.join("/")}`;
if (this.queryParameters) {
const queryParams = new URLSearchParams(Object.entries(this.queryParameters).map(([key, value]) => [key, String(value)])).toString();
if (queryParams) {
url += `?${queryParams}`;
}
}
return {
url,
headers: this.headers,
params: this.queryParameters || {},
body: this.body,
method: this.method,
};
}
async fetch(requestInit) {
let url = `${this.baseURL}/${this.segments.join("/")}`;
if (this.queryParameters) {
const queryParams = new URLSearchParams(Object.entries(this.queryParameters).map(([key, value]) => [key, String(value)])).toString();
if (queryParams) {
url += `?${queryParams}`;
}
}
return await fetchJson(url, {
...requestInit,
headers: this.headers,
method: this.method,
body: this.body,
});
}
}
const API_TIMEOUT = 15000;
const BASE_URL = "api.railway.zennozenith.com";
const API_VRSION = "v1";
const DEFAULT_PROTOCOL = "https";
export class Client {
#apiCalls = 0;
apiKey;
baseUrl;
apiVersion;
apiTimeout;
protocol;
trains;
stations;
schedules;
trainsBtwStations;
healthCheck;
headers;
constructor(options = {}) {
this.headers = {};
this.apiKey = options.API_KEY || null;
this.baseUrl = options.BASE_URL || BASE_URL;
this.apiVersion = options.API_VERSION || API_VRSION;
this.apiTimeout = options.API_TIMEOUT || API_TIMEOUT;
this.protocol = options.PROTOCOL || DEFAULT_PROTOCOL;
this.healthCheck = new HealthCheck(this);
this.trains = new Trains(this);
this.stations = new Stations(this);
this.schedules = new Schedules(this);
this.trainsBtwStations = new TrainsBtwStations(this);
if (this.apiKey) {
this.headers["x-api-key"] = this.apiKey;
}
}
get apiCalls() {
return this.#apiCalls;
}
}
//# sourceMappingURL=utils.js.map