-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (79 loc) · 2.59 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
const sqlite3 = require('sqlite3').verbose();
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
let db = new sqlite3.Database('./db/articles.db', (err) => {
if (err) {
return console.error(err.message);
}
db.run(`
CREATE TABLE IF NOT EXISTS articles(
id INTEGER not null constraint articles_pk primary key autoincrement,
title TEXT,
content TEXT
);
create unique index articles_id_uindex
on articles (id);
`);
console.log('Conected to the SQlite database.');
});
app.listen(3000, function () {
console.log('server is running, port 3000')
});
app.post('/api/articles', function (req, res) {
db.serialize(() => {
db.run('INSERT INTO articles (title, content) VALUES (?, ?)', [req.body.title, req.body.content], function (err) {
if (err) {
res.status(400).json({"error": err.message})
}
res.json({
"status": true
});
});
});
});
app.get('/api/articles/:id', function (req, res) {
db.serialize(() => {
db.each('SELECT id ID, title TITLE, content CONTENT FROM articles WHERE id =?', [req.params.id], function (err, row) {
if (err) {
res.status(400).json({"error": err.message})
return;
}
res.json({
"status": true,
"data": [row]
});
});
});
});
app.delete('/api/articles/:id', function (req, res) {
db.serialize(() => {
db.run('DELETE FROM articles WHERE id = ?', [req.params.id], function (err) {
if (err) {
res.status(400).json({"error": err.message})
return console.error(err.message);
}
res.json({
"status": true,
})
});
});
});
app.patch('/api/articles/:id', function (req, res) {
db.serialize(() => {
db.run('UPDATE articles SET title = ?, content = ? WHERE id = ?', [req.body.title, req.body.content, req.params.id], function (err) {
if (err) res.status(400).json({"error": err.message});
});
db.each('SELECT id ID, title TITLE, content CONTENT FROM articles WHERE id =?', [req.params.id], function (err, row) {
if (err) {
res.status(400).json({"error": err.message})
return;
}
res.json({
"status": true,
"data": [row]
});
});
});
});