summaryrefslogtreecommitdiff
path: root/nodejs/database/ships.js
blob: f9eb6686ba7ea993b8a863a8b9464e21a1a0ab65 (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
import db from './db.js';

const addShipStatement = db.prepare(`INSERT INTO ships(data) VALUES (json(?));`);
const getShipStatement = db.prepare(`SELECT data FROM ships WHERE data->>'symbol' = ?;`);
const getShipsAtStatement = db.prepare(`SELECT data FROM ships WHERE data->>'$.nav.systemSymbol' = ?;`);
const setShipCargoStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.cargo', json(:cargo)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`);
const setShipFuelStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.fuel', json(:fuel)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`);
const setShipNavStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.nav', json(:nav)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`);
const updateShipStatement = db.prepare(`UPDATE ships SET data = json(:data) WHERE data->>'symbol' = :symbol;`);

export function getShip(symbol) {
	const data = getShipStatement.get(symbol);
	if (data === undefined) {
		return null;
	}
	return JSON.parse(data.data);
}

export function getShipsAt(symbol) {
	const data = getShipsAtStatement.all(symbol);
	if (data === undefined) {
		return null;
	}
	return data.map(elt => JSON.parse(elt.data));
}


export function setShip(data) {
	if (getShip(data.symbol) === null) {
		return addShipStatement.run(JSON.stringify(data)).lastInsertRowid;
	} else {
		return updateShipStatement.run({
			data: JSON.stringify(data),
			symbol: data.symbol,
		}).changes;
	}
}

export function setShipCargo(symbol, cargo) {
	return setShipCargoStatement.run({
		cargo: JSON.stringify(cargo),
		symbol: symbol,
	}).changes;
}

export function setShipFuel(symbol, fuel) {
	return setShipFuelStatement.run({
		fuel: JSON.stringify(fuel),
		symbol: symbol,
	}).changes;
}

export function setShipNav(symbol, nav) {
	return setShipNavStatement.run({
		nav: JSON.stringify(nav),
		symbol: symbol,
	}).changes;
}