From a1d6b03ec98abbc073b5b73b631da6ea3eae4eb9 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Wed, 27 Mar 2024 15:20:14 +0100 Subject: [node] finished the great typescript rewrite --- nodejs/automation/init.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 nodejs/automation/init.ts (limited to 'nodejs/automation/init.ts') diff --git a/nodejs/automation/init.ts b/nodejs/automation/init.ts new file mode 100644 index 0000000..b3c7a40 --- /dev/null +++ b/nodejs/automation/init.ts @@ -0,0 +1,43 @@ +import * as dbAgents from '../database/agents.ts'; +import * as db from '../database/db.ts'; +import * as dbContracts from '../database/contracts.ts'; +import * as dbShips from '../database/ships.ts'; +import * as dbTokens from '../database/tokens.ts'; +import { Agent } from '../model/agent.ts'; +import { Response } from '../model/api.ts'; +import { Contract } from '../model/contract.ts'; +import { Ship } from '../model/ship.ts'; +import * as api from '../lib/api.ts'; +import * as ships from '../lib/ships.ts'; + +const symbol = process.env.NODE_ENV === 'test' ? 'ADYXAX-0' : 'ADYXAX-JS'; + +// This function registers then inits the database +export async function init(): Promise { + const response = await fetch('https://api.spacetraders.io/v2/register', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + symbol: symbol, + faction: "COSMIC", + }), + }); + const json = await response.json() as Response<{agent: Agent, contract: Contract, ship: Ship, token: string}>; + 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(); +} -- cgit v1.2.3