-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
94 lines (80 loc) · 2.02 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
require('dotenv').config();
const express = require('express');
const { initDb } = require('./lib/database');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 8081;
const {
getEntries,
getEntry,
setEntry,
updateEntry,
deleteEntry
// searchEntries
} = require('./lib/entries');
//middleware
app.use(express.json({ extended: false }));
app.get('/api/entries/', async (req, res) => {
try {
const entries = await getEntries();
res.send(entries);
} catch (error) {
console.error(error);
res.end();
}
});
app.get('/api/entries/:entryId', async (req, res) => {
try {
const result = await getEntry(req.params.entryId);
res.send(result);
} catch (error) {
console.error(error);
res.end();
}
});
//post routes
app.post('/api/entries/', (req, res) => {
try {
req.body;
setEntry(req.body);
res.end();
} catch (error) {
console.error(error);
res.end();
}
});
// patch routes
app.patch('/api/entries/edit/:entryId', async (req, res) => {
try {
const entryId = req.params.entryId;
const value = req.body;
await updateEntry(entryId, value);
console.log(req.body);
res.end();
} catch (error) {
console.error(error);
res.end();
}
});
// delete routes
app.delete('/api/entries/:entryId', async (req, res) => {
try {
await deleteEntry(req.params.entryId);
res.send('Entry deleted');
} catch (error) {
console.error(error);
res.send('Sorry, deleting your Entry was not possible.');
}
});
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
initDb(process.env.DB_URL, process.env.DB_NAME).then(async () => {
console.log(`Database ${process.env.DB_NAME} is connected`);
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${process.env.PORT || '8081'}`);
});
});