summaryrefslogtreecommitdiff
path: root/nodejs/lib/systems.ts
blob: 97aa6e3a0915aebede3d54bd4d31f5458c954622 (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
import {
	debugLog,
	send,
	sendPaginated,
} from './api.ts';
import * as dbMarkets from '../database/markets.ts';
import * as dbSystems from '../database/systems.ts';
import {
	Market,
	System,
	Waypoint
} from './types.ts'
import { systemFromWaypoint } from './utils.ts';

export async function market(waypointSymbol: string): Promise<Market> {
    const data = dbMarkets.getMarketAtWaypoint(waypointSymbol);
	if (data) { return data; }
	const systemSymbol = systemFromWaypoint(waypointSymbol);
	let response = await send<Market>({endpoint: `/systems/${systemSymbol}/waypoints/${waypointSymbol}/market`});
	if (response.error) {
		debugLog(response);
		throw response;
	}
	dbMarkets.setMarket(response.data);
	return response.data;
}

//export async function shipyard(waypoint: string): Promise<unknown> {
//	// TODO database caching
//	const systemSymbol = systemFromWaypoint(waypoint);
//	return await send({endpoint: `/systems/${systemSymbol}/waypoints/${waypoint}/shipyard`});
//}

export async function system(symbol: string): Promise<System> {
	let data = dbSystems.getSystem(symbol);
	if (data) { return data; }
	const response = await send<System>({endpoint: `/systems/${symbol}`});
	if (response.error) {
		debugLog(response);
		throw response;
	}
	dbSystems.setSystem(response.data);
	return response.data;
}

// Retrieves a list of waypoints that have a specific trait like a SHIPYARD or a MARKETPLACE
export async function trait(system: string, trait: string): Promise<Array<Waypoint>> {
	const ws = await waypoints(system);
	return ws.filter(w => w.traits.some(t => t.symbol === trait));
}

// Retrieves a list of waypoints that have a specific type like ASTEROID_FIELD
export async function type(system: string, typeSymbol: string): Promise<Array<Waypoint>> {
	const ws = await waypoints(system);
	return ws.filter(s => s.type === typeSymbol);
}

export async function waypoints(systemSymbol: string): Promise<Array<Waypoint>> {
	const s = await system(systemSymbol);
	const updated = dbSystems.getSystemUpdated(systemSymbol);
	// TODO handle uncharted systems
	if (updated) return s.waypoints;
	const waypoints = await sendPaginated<Waypoint>({endpoint: `/systems/${systemSymbol}/waypoints`});
	dbSystems.setSystemWaypoints(systemSymbol, waypoints);
	return waypoints;
}