From 8bf9b5619d71ac6e383dd3c2a26e4d36e86db8f9 Mon Sep 17 00:00:00 2001 From: asenawritescode Date: Tue, 6 Aug 2024 09:54:25 +0300 Subject: [PATCH] chore: initial database setup --- database/index.js | 6 ++++++ database/mock.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++ database/sqlite.js | 37 +++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 database/index.js create mode 100644 database/mock.js create mode 100644 database/sqlite.js diff --git a/database/index.js b/database/index.js new file mode 100644 index 0000000..695aa9c --- /dev/null +++ b/database/index.js @@ -0,0 +1,6 @@ +class DatabaseSessionManager { + constructor() { + this.sessions = []; + } + +} \ No newline at end of file diff --git a/database/mock.js b/database/mock.js new file mode 100644 index 0000000..79f916d --- /dev/null +++ b/database/mock.js @@ -0,0 +1,52 @@ +'use strict'; + +class InMemorySessionManager{ + constructor(){ + this.sessions = []; + } + + createNew(session){ + this.sessions.push(session); + + return session; + } + + get(msisdn) { + var session = null; + this.sessions.forEach(element => { + if (element !== null && element.msisdn === msisdn){ + session = element; + } + }); + + return session; + } + + close(session){ + const testing = (e) => e.msisdn === session.msisdn; + + const index = this.sessions.findIndex(testing); + + if(index > -1){ + this.sessions.splice(index, 1); + } + } + + update(session){ + var ses = [] + + for(var i = 0; i < this.sessions.length; i++){ + if(this.sessions[i] !== null && this.sessions[i].msisdn !== session.msisdn) { + ses.push(session); + } + } + + var n_session = session; + + ses.push(n_session); + + this.sessions = ses; + } +} + +module.exports = InMemorySessionManager; \ No newline at end of file diff --git a/database/sqlite.js b/database/sqlite.js new file mode 100644 index 0000000..46efdc9 --- /dev/null +++ b/database/sqlite.js @@ -0,0 +1,37 @@ +'use strict'; + +const Database = require('better-sqlite3'); + +class SQLiteSessionManager { + + constructor(file) { + this.db = new Database(file); + + // This is optional to improve performance + this.db.pragma('journal_mode = WAL'); + + this.db.prepare('CREATE TABLE IF NOT EXISTS sessions (msisdn TEXT, prompt TEXT, menu TEXT, session TEXT)').run(); + } + + createNew(session) { + this.db.prepare('INSERT INTO sessions VALUES (?, ?, ?, ?)').run(session.msisdn, session.prompt, session.menu, JSON.stringify(session)); + return session; + } + + get(msisdn) { + const row = this.db.prepare('SELECT * FROM sessions WHERE msisdn = ?').get(msisdn); + return row ? JSON.parse(row.session) : null; + } + + close(session) { + this.db.prepare('DELETE FROM sessions WHERE msisdn = ?').run(session.msisdn); + } + + update(session) { + this.db.prepare('UPDATE sessions SET session = ? WHERE msisdn = ?').run(JSON.stringify(session), session.msisdn); + } + + +} + +module.exports = SQLiteSessionManager; \ No newline at end of file