mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
we have persistence!
This commit is contained in:
@@ -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) => {
|
||||
|
||||
Reference in New Issue
Block a user