-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSequlizeSQLiteCRUDBook.js
More file actions
92 lines (82 loc) · 2.13 KB
/
SequlizeSQLiteCRUDBook.js
File metadata and controls
92 lines (82 loc) · 2.13 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const express = require('express');
const Seqelize = require('sequelize');
const app = express();
app.use(express.json());
const sequelize = new Seqelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
storage: './Database/SQBooks.sqlite'
});
const Book = sequelize.define('Book', {
id: {
type: Seqelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
title: {
type: Seqelize.STRING,
allowNull: false
},
author: {
type: Seqelize.STRING,
allowNull: false
}
});
sequelize.sync();
app.get('/books', (req, res) => {
Book.findAll().then(books => {
res.json(books);
}).catch(err => {
res.status(500).send(err);
});
});
app.get('/books/:id', (req, res) => {
Book.findByPk(req.params.id).then(book => {
if (!book) {
res.status(404).send('Book not found');
} else {
res.json(book);
}
}).catch(err => {
res.status(500).send(err);
});
});
app.post('/books', (req, res) => {
Book.create(req.body).then(book => {
res.send(book);
}).catch(err => {
res.status(500).send(err);
});
});
app.put('/books/:id', (req, res) => {
Book.findByPk(req.params.id).then(book => {
if (!book) {
res.status(404).send('Book not found');
} else {
book.update(req.body).then(() => {
res.send(book);
}).catch(err => {
res.status(500).send(err);
});
}
}).catch(err => {
res.status(500).send(err);
});
});
app.delete('/books/:id', (req, res) => {
Book.findByPk(req.params.id).then(book => {
if (!book) {
res.status(404).send('Book not found');
} else {
book.destroy().then(() => {
res.send({});
}).catch(err => {
res.status(500).send(err);
});
}
}).catch(err => {
res.status(500).send(err);
});
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));