Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (60 loc) · 1.76 KB
/
Copy pathserver.js
File metadata and controls
73 lines (60 loc) · 1.76 KB
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
const express = require('express');
const http = require('http');
const path = require('path');
const { Datastore } = require('nedb-async-await');
const cors = require('cors');
const PORT = process.env.PORT || 3000;
const app = express();
const httpServer = http.Server(app);
app.use(cors());
const db = {};
db.posts = Datastore({
filename: path.resolve(path.dirname(''), './database/posts.db'),
autoload: true,
});
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/api', (req, res) => {
res.json({ status: 'Server works' });
});
// create
app.post('/api/posts', async (req, res) => {
const { title, content } = req.body;
const status = await db.posts.insert({ title, content });
res.json(status);
});
// get list
app.get('/api/posts', async (req, res) => {
const posts = await db.posts.find({});
res.json({ posts });
});
// get single entry
app.get('/api/posts/:id', async (req, res) => {
const post = await db.posts.find({ _id: req.params.id });
res.json({ post });
});
// update
app.put('/api/posts/:id', async (req, res) => {
const { title, content } = req.body;
const status = await db.posts.update(
{ _id: req.params.id },
{ title, content }
);
res.json(status);
});
// delete
app.delete('/api/posts/:id', async (req, res) => {
const status = await db.posts.remove({ _id: req.params.id });
res.json(status);
});
// serve static angular app
app.use(
'/',
express.static(path.resolve(path.dirname(''), './client/dist/client'))
);
app.get('*', (req, res) => {
res.sendFile(
path.resolve(path.dirname(''), './client/dist/client/index.html')
);
});
httpServer.listen(PORT, () => console.warn(`Listening on port: ${PORT}`));