summaryrefslogtreecommitdiff
path: root/nodejs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--nodejs/database/000_init.sql9
-rw-r--r--nodejs/database/agents.js16
-rw-r--r--nodejs/database/contracts.js24
-rw-r--r--nodejs/lib/contracts.js5
4 files changed, 53 insertions, 1 deletions
diff --git a/nodejs/database/000_init.sql b/nodejs/database/000_init.sql
index c06d2d3..9c06622 100644
--- a/nodejs/database/000_init.sql
+++ b/nodejs/database/000_init.sql
@@ -5,3 +5,12 @@ CREATE TABLE tokens (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);
+CREATE TABLE agents (
+ id INTEGER PRIMARY KEY,
+ data TEXT NOT NULL
+);
+CREATE TABLE contracts (
+ id INTEGER PRIMARY KEY,
+ data TEXT NOT NULL
+);
+CREATE UNIQUE INDEX contracts_data_id ON contracts (json_extract(data, '$.id'));
diff --git a/nodejs/database/agents.js b/nodejs/database/agents.js
new file mode 100644
index 0000000..fe24d8c
--- /dev/null
+++ b/nodejs/database/agents.js
@@ -0,0 +1,16 @@
+import db from './db.js';
+
+const addAgentStatement = db.prepare(`INSERT INTO agents(data) VALUES (json(?));`);
+const getAgentStatement = db.prepare(`SELECT data FROM agents;`);
+
+export function addAgent(agent) {
+ return addAgentStatement.run(JSON.stringify(agent)).lastInsertRowid;
+}
+
+export function getAgent() {
+ const data = getAgentStatement.get();
+ if (data === undefined) {
+ return null;
+ }
+ return data.data;
+}
diff --git a/nodejs/database/contracts.js b/nodejs/database/contracts.js
new file mode 100644
index 0000000..8790701
--- /dev/null
+++ b/nodejs/database/contracts.js
@@ -0,0 +1,24 @@
+import db from './db.js';
+
+const addContractStatement = db.prepare(`INSERT INTO contracts(data) VALUES (json(?));`);
+const getContractStatement = db.prepare(`SELECT data FROM contracts WHERE data->>'id' = ?;`);
+const updateContractStatement = db.prepare(`UPDATE contracts SET data = json(:data) WHERE data->>'id' = :id;`);
+
+export function getContract(id) {
+ const data = getContractStatement.get(id);
+ if (data === undefined) {
+ return null;
+ }
+ return data.data;
+}
+
+export function setContract(data) {
+ if (getContract(data.id) === null) {
+ return addContractStatement.run(JSON.stringify(data)).lastInsertRowid;
+ } else {
+ return updateContractStatement.run({
+ data: JSON.stringify(data),
+ id: data.id,
+ }).changes;
+ }
+}
diff --git a/nodejs/lib/contracts.js b/nodejs/lib/contracts.js
index 316e181..e4ba2ae 100644
--- a/nodejs/lib/contracts.js
+++ b/nodejs/lib/contracts.js
@@ -1,3 +1,4 @@
+import * as dbContracts from '../database/contracts.js';
import * as api from './api.js';
import * as dbShips from '../database/ships.js';
@@ -6,7 +7,9 @@ export async function accept(ctx) {
}
export async function contracts() {
- return await api.send({endpoint: '/my/contracts'});
+ const contracts = await api.send({endpoint: '/my/contracts', page: 1});
+ contracts.forEach(contract => dbContracts.setContract(contract));
+ return contracts;
}
export async function deliver(ctx) {