-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.js
80 lines (71 loc) · 1.46 KB
/
database.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
import sqlite from 'sqlite3'
export function connectDB() {
return new sqlite.Database('data', (err) => {
if (err) {
throw err
}
console.log('db created')
})
}
/**
*
* @param {sqlite.Database} db
*/
export function initTable(db) {
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS product (
id INTEGER PRIMARY KEY AUTOINCREMENT,
photo TEXT NOT NULL,
name VARCHAR(56) NOT NULL,
price INTEGER NOT NULL
);`)
})
}
/**
*
* @param {sqlite.Database} db
* @param {string} name
* @param {number} price
* @param {string} photo
*/
export function insertProduct(db, name, price, photo) {
db.run('INSERT INTO product (photo,name,price) VALUES ($photo,$name,$price)', { $photo: photo, $name: name, $price: price }, (err) => {
if (err) {
throw err
}
console.log('product saved')
})
}
/**
*
* @param {sqlite.Database} db
*/
export function getProduct(db) {
return new Promise((resolve, reject) => {
db.all('SELECT * FROM product', (err, result) => {
if (err) {
reject(err)
}
if (result) {
resolve(result)
} else {
resolve([])
}
})
})
}
/**
*
* @param {sqlite.Database} db
* @param {number} id
*/
export function deleteProduct(db, id) {
return new Promise((resolve, reject) => {
db.run('DELETE FROM product WHERE id = ?', id, (err) => {
if(err) {
reject(err)
}
resolve()
})
})
}