-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
41 lines (32 loc) · 885 Bytes
/
db.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
const sqlite3 = require('sqlite3');
const dbName = 'later.sqlite';
const db = new sqlite3.Database(dbName);
db.serialize(() => {
const sql = `
CREATE TABLE IF NOT EXISTS articles
(id integer primary key, title, content TEXT)
`;
// creates an 'articles' table if there isn't one
db.run(sql);
});
class Article {
static all(cb) {
db.all('SELECT * FROM articles', cb);
}
static find(id, cb) {
db.get('SELECT * FROM articles WHERE id = ?', id, cb);
}
static create(data, cb) {
// parameters specified with ?
const sql = 'INSERT INTO articles(title, content) VALUES (?, ?)';
db.run(sql, data.title, data.content, cb);
}
static delete(id, cb) {
if (!id) {
return cb(new Error('Please provide an id'));
}
db.run('DELETE FROM articles WHERE id = ?', id, cb);
}
}
module.exports = db;
module.exports.Article = Article;