we have persistence!

This commit is contained in:
Ken
2019-02-18 12:02:55 -08:00
parent a709417642
commit d98bda36ad
5 changed files with 50 additions and 16 deletions

View File

@@ -1,4 +1,5 @@
// @ts-check
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
@@ -6,6 +7,20 @@ const app = express();
const store = {
/** @type {any} */
read() {
if (fs.existsSync('tmp.json')) {
store.todos = JSON.parse(fs.readFileSync('tmp.json').toString());
} else {
store.todos = {};
}
return store.todos;
},
save() {
fs.writeFileSync('tmp.json', JSON.stringify(store.todos));
},
todos: {}
};
@@ -13,24 +28,28 @@ app.use(bodyParser.json());
app.use(cors());
app.get('/todos', (req, res) => {
res.json(store.todos);
res.json(store.read());
});
app.put('/todos/:id', (req, res) => {
store.todos[req.params.id] = req.body;
store.save();
res.json('ok');
});
app.post('/todos/:id', (req, res) => {
store.todos[req.params.id] = req.body;
store.save();
});
app.delete('/todos/:id', (req, res) => {
delete store.todos[req.params.id];
store.save();
});
app.post('/todos', req => {
store.todos = req.body;
store.save();
});
app.get('/hello', (req, res) => {