summaryrefslogtreecommitdiff
path: root/nodejs/automation/init.js
blob: b921942bc54d0c7682fe2074b47b36140b855abc (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
import * as dbAgents from '../database/agents.js';
import * as db from '../database/db.js';
import * as dbContracts from '../database/contracts.js';
import * as dbShips from '../database/ships.js';
import * as dbTokens from '../database/tokens.js';
import * as api from '../lib/api.js';
import * as ships from '../lib/ships.js';

// This function registers then inits the database
export async function init() {
	const response = await fetch('https://api.spacetraders.io/v2/register', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
		},
		body: JSON.stringify({
			symbol: "ADYXAX-JS",
			faction: "COSMIC",
		}),
	});
	const json = await response.json();
	if (json.error !== undefined) {
		switch(json.error?.code) {
		case 4111:  // 4111 means the agent symbol has already been claimed so no server reset happened
			return;
		default:
			throw json;
		}
	}
	db.reset();
	dbAgents.addAgent(json.data.agent);
	dbContracts.setContract(json.data.contract);
	dbShips.setShip(json.data.ship);
	dbTokens.addToken(json.data.token);
	// Temporary fix to fetch the data on the startup probe
	ships.ships();
}