-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbLayer.js
86 lines (77 loc) · 1.88 KB
/
dbLayer.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
import { SQLite } from 'expo'
const db = SQLite.openDatabase('db.db')
const createTableIfNotExists = () => {
const query = `
create table if not exists entries
(
id integer primary key not null,
scannedAt datetime not null,
content string not null,
type string not null
)
`
db.transaction(tx => {
tx.executeSql(query)
})
}
const createEntry = ({ scannedAt, content, type}, success) => {
db.transaction(
tx => {
tx.executeSql(
'insert into entries (scannedAt, content, type) values(?, ?, ?)',
[scannedAt, content, type],
)
},
error => console.log('Error creating entry', error),
success,
)
}
const getEntries = success => {
return new Promise((resolve, reject) => {
db.transaction(
tx => {
tx.executeSql('select * from entries order by scannedAt DESC', [], (_, { rows: { _array } }) =>
resolve(_array),
)
},
error => reject(console.log('Error querying entries: ', error)),
success,
)
})
}
const isLastEntry = content =>
new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'select max(id), content from entries',
[],
(_, { rows: { _array } }) => resolve(_array[0].content === content),
)
})
})
const deleteEntry = (id, success) => {
db.transaction(
tx => {
tx.executeSql('delete from entries where id = ?;', [id])
},
error => console.log(`Error deleting entry with id ${id}: `, error),
null,
)
}
const deleteLastEntry = (success) => {
db.transaction(
tx => {
tx.executeSql('delete from entries where id = (select max(id) from entries)')
},
error => console.log(`Error deleting last entry: `, error),
success,
)
}
export default {
createTableIfNotExists,
createEntry,
getEntries,
isLastEntry,
deleteEntry,
deleteLastEntry,
}