UNPKG

ddnet

Version:

A typescript npm package for interacting with data from ddnet.org

92 lines 3.05 kB
import axios from 'axios'; import { _Schema_status } from '../../schemas/other/status.js'; import { DDNetError, dePythonifyTime } from '../../util.js'; import { ServerStatus } from './ServerStatus.js'; /** * Represents DDNet server statuses. */ export class ServerListStatuses { //#region Declarations /** * Raw releases data. */ #rawData; // Marked private with vanilla JS syntax for better logging. servers; lastUpdatedTimestamp; //#endregion /** * Create a new instance of {@link ServerListStatuses} from API data. * Not intended to be used, use {@link new ServerListStatuses.new} instead. */ constructor( /** * The raw data for this. */ rawData) { this.populate(rawData); } /** * Fetch, parse and construct a new {@link ServerListStatuses} instance. */ static async new() { const response = await this.makeRequest(); if (response instanceof DDNetError) throw response; const parsed = this.parseObject(response); if (!parsed.success) throw parsed.error; return new this(parsed.data); } /** * Parse an object using the {@link _Schema_status server status raw data zod schema}. */ static parseObject( /** * The object to be parsed. */ data) { const parsed = _Schema_status.safeParse(data); // wtf if (parsed.success) return { success: true, data: parsed.data }; return { success: false, error: new DDNetError(parsed.error.message, parsed.error) }; } /** * Fetch the server status data from the API. */ static async makeRequest() { const url = 'https://ddnet.org/status/json/stats.json'; const response = await axios.get(url).catch((err) => new DDNetError('An error has occurred while fetching the response from ddnet.org!', err)); if (response instanceof DDNetError) return response; const data = response.data; if (typeof data === 'string') return new DDNetError(`Invalid response!`, data); return data; } /** * Populate the object with the raw server status data. */ populate( /** * The raw server status data. */ rawData) { this.#rawData = rawData; this.servers = this.#rawData.servers.map(srv => new ServerStatus(srv)); this.lastUpdatedTimestamp = dePythonifyTime(parseInt(this.#rawData.updated)); return this; } /** * Refresh the server status data. */ async refresh() { const data = await ServerListStatuses.makeRequest(); if (data instanceof DDNetError) throw new DDNetError(`Failed to refresh releases`, data); const parsed = ServerListStatuses.parseObject(data); if (!parsed.success) throw new DDNetError(`Failed to refresh releases`, parsed.error); return this.populate(parsed.data); } } //# sourceMappingURL=ServerListStatuses.js.map