From 36cc33f9e96a38ecea98ac8d26275b4828347d80 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Sat, 1 Jul 2023 23:13:13 +0200 Subject: Moved the nodejs agent to its own subfolder to make room for my haskell agent --- nodejs/lib/systems.js | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 nodejs/lib/systems.js (limited to 'nodejs/lib/systems.js') diff --git a/nodejs/lib/systems.js b/nodejs/lib/systems.js new file mode 100644 index 0000000..e03da6c --- /dev/null +++ b/nodejs/lib/systems.js @@ -0,0 +1,68 @@ +import * as api from './api.js'; +import * as db from '../database/systems.js'; + +// Retrieves a shipyard's information for ctx.symbol +export async function shipyard(ctx) { + const systemSymbol = ctx.symbol.match(/([^-]+-[^-]+)/)[1]; // TODO generalise this extraction + console.log(systemSymbol); + return await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${ctx.symbol}/shipyard`}); +} + +// Retrieves the system's information for ctx.symbol and caches it in the database +export async function system(ctx) { + let s = db.getSystem(ctx.symbol); + if (s === null) { + const response = await api.send({endpoint: `/systems/${ctx.symbol}`}); + if (response.error !== undefined) { + switch(response.error.code) { + case 404: + throw `Error retrieving info for system ${ctx.symbol}: ${response.error.message}`; + default: // yet unhandled error + throw response; + } + } + s = response.data; + db.setSystem(s); + } + return s; +} + +// Retrieves a list of waypoints that have a specific ctx.trait like a SHIPYARD or a MARKETPLACE in the system ctx.symbol +export async function trait(ctx) { + const w = await waypoints(ctx); + return w.filter(s => s.traits.some(t => t.symbol === ctx.trait)); +} + +// Retrieves a list of waypoints that have a specific ctx.type like ASTEROID_FIELD in the system ctx.symbol +export async function type(ctx, response) { + const w = await waypoints(ctx); + return w.filter(s => s.type === ctx.type); +} + +// Retrieves the system's information for ctx.symbol and caches it in the database +export async function waypoints(ctx) { + await system(ctx); + let updated = db.getSystemUpdated(ctx.symbol); + // TODO handle uncharted systems + if (updated === null) { + let waypoints = []; + for (let page=1; true; ++page) { + const response = await api.send({endpoint: `/systems/${ctx.symbol}/waypoints?limit=20&page=${page}`, priority: 98}); + if (response.error !== undefined) { + switch(response.error.code) { + case 404: + throw `Error retrieving waypoints for system ${ctx.symbol}: ${response.error.message}`; + default: // yet unhandled error + throw response; + } + } + waypoints = waypoints.concat(response.data); + if (response.meta.total <= response.meta.limit * page) { + break; + } + } + db.setSystemWaypoints(ctx.symbol, waypoints); + return waypoints; + } + return db.getSystem(ctx.symbol).waypoints; +} -- cgit v1.2.3