From e03bb9061103cb11cd3c55a32fa688bde8c01e3b Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Sat, 2 Sep 2023 02:16:42 +0200 Subject: [javascript] added contracts and agent database management --- nodejs/database/000_init.sql | 9 +++++++++ nodejs/database/agents.js | 16 ++++++++++++++++ nodejs/database/contracts.js | 24 ++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 nodejs/database/agents.js create mode 100644 nodejs/database/contracts.js (limited to 'nodejs/database') 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; + } +} -- cgit v1.2.3