-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
77 lines (65 loc) · 1.7 KB
/
Copy pathserver.js
File metadata and controls
77 lines (65 loc) · 1.7 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
74
75
76
77
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const express = require('express');
const cors = require('cors');
const server = express();
const port = 5000;
// knex
const env = 'development';
const config = require('./knexfile.js')[env];
const knex = require('knex')(config);
// config
server.use(express.json());
server.use(bodyParser.json());
server.use(cors());
//OPENING message
server.get('/', (req, res) => {
res.json({ message: "Welcome to the API" });
});
// READ DATA
server.get('/posts', (req, res) => {
// shows selected query in console
// console.log('\n' + knex('posts').toString())
knex('posts').then((results) => {
res.json(results);
})
})
// READ 1 object of DATA by id
server.get('/posts/:id', (req, res) => {
const post = posts.find(post => post.id == req.params.id);
if (post) {
res.status(200).json(post);
} else {
res.status(404).send({ msg: 'content not found' });
}
});
// CREATE 1 object of DATA
server.post('/posts', (req, res) => {
console.log(req.body)
knex('posts').insert({
author: req.body.author,
content: req.body.content,
}).then((results) => {
res.send(200);
})
})
// UPDATE 1 object of DATA
server.put('/posts/:id', (req, res) => {
knex('posts').update({
author: req.body.author,
content: req.body.content,
upvotes: req.body.upvotes
}).where('id', req.params.id)
.then((results) => {
res.send(200);
})
})
// DELETE DATA
server.delete('/posts/:id', (req, res) => {
knex('posts').delete().where('id', req.params.id).then(() => {
res.send(200);
})
})
server.listen(port, () => {
console.log(`\n Server listening on port ${port} \n`);
});