summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJoe Carstairs <65492573+Sycamost@users.noreply.github.com>2024-03-07 22:21:39 +0000
committerJoe Carstairs <65492573+Sycamost@users.noreply.github.com>2024-03-07 22:22:21 +0000
commit52cbc5ac4e0b2a4f81d70050ba2e83ad8541db0d (patch)
tree87d5e31f42bd2172f4cff5f4c9d7fd167c543212 /src
parent88baf168df46d1f03244f5669bb672a712416759 (diff)
saves stuff in data.json
Diffstat (limited to 'src')
-rw-r--r--src/app.js3
-rw-r--r--src/db.js30
2 files changed, 32 insertions, 1 deletions
diff --git a/src/app.js b/src/app.js
index 9b47728..a374995 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1,9 +1,10 @@
const bodyParser = require('body-parser');
const express = require('express');
-const { isSubscribed, getSubscriptions, getSubscriptionFromNumber, subscribe } = require('./db');
+const { isSubscribed, getSubscriptions, getSubscriptionFromNumber, subscribe, load: loadData } = require('./db');
const { sendTextMessage } = require('./sendTextMessage');
const { MessagingResponse } = require('twilio').twiml;
+loadData();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
diff --git a/src/db.js b/src/db.js
index ba37a30..c277f7c 100644
--- a/src/db.js
+++ b/src/db.js
@@ -1,6 +1,8 @@
// Ideally, we should write to a file and read it at app start in case of crashes.
// An actual SQL database would probably be overkill.
+const { readFileSync, writeFile } = require("fs");
+
/** @type Array<{ name: string, number: string }> */
const subscriptions = [];
@@ -11,6 +13,7 @@ const subscriptions = [];
function subscribe(number, name) {
const subscription = { name, number };
subscriptions.push(subscription);
+ void save();
return subscription;
}
@@ -37,9 +40,36 @@ function getSubscriptionFromNumber(number) {
return subscriptions.find(sub => sub.number === number);
}
+async function save() {
+ try {
+ await writeFile('../data.json', JSON.stringify({ subscriptions }));
+ } catch (err) {
+ if (typeof err === 'string') {
+ console.error(`Error writing data: ${err}`);
+ } else {
+ console.error(`Error writing data: ${JSON.stringify(err)}`);
+ }
+ }
+}
+
+function load() {
+ try {
+ const data = JSON.parse(readFileSync('../data.json'));
+ while (subscriptions.pop()) {}
+ subscriptions.push(...data['subscriptions']);
+ } catch (err){
+ if (typeof err === 'string') {
+ console.error(`Error reading data: ${err}`);
+ } else {
+ console.error(`Error reading data: ${JSON.stringify(err)}`);
+ }
+ }
+}
+
module.exports = {
subscribe,
isSubscribed,
getSubscriptions,
getSubscriptionFromNumber,
+ load,
}; \ No newline at end of file