diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/app.js | 3 | ||||
| -rw-r--r-- | src/db.js | 30 |
2 files changed, 32 insertions, 1 deletions
@@ -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 })); @@ -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 |
