diff options
| author | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2024-03-07 22:21:39 +0000 |
|---|---|---|
| committer | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2024-03-07 22:22:21 +0000 |
| commit | 52cbc5ac4e0b2a4f81d70050ba2e83ad8541db0d (patch) | |
| tree | 87d5e31f42bd2172f4cff5f4c9d7fd167c543212 /src/db.js | |
| parent | 88baf168df46d1f03244f5669bb672a712416759 (diff) | |
saves stuff in data.json
Diffstat (limited to 'src/db.js')
| -rw-r--r-- | src/db.js | 30 |
1 files changed, 30 insertions, 0 deletions
@@ -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 |
