summaryrefslogtreecommitdiff
path: root/nodejs/lib/systems.js
blob: fefa5cd5bce4fa227b0367fe81c7489a6579fa24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import * as api from './api.js';
import * as db from '../database/systems.js';
import * as utils from './utils.js';


// Retrieves a shipyard's information for ctx.symbol
export async function shipyard(ctx) {
	const systemSymbol = utils.systemFromWaypoint(ctx.symbol);
	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;
}