-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_import_export.js
63 lines (50 loc) · 1.48 KB
/
app_import_export.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
/*
These are the functions used to download and import the entire database.
*/
function exportJSON (done) {
db.allDocs({include_docs: true, descending: true}, function (err, doc) {
const jsonLink = document.createElement('a')
jsonLink.download = `pouchDB-${Date.now()}.json`
jsonLink.href = `data:application/json;charset=utf-8, ${JSON.stringify(doc.rows)}`
jsonLink.click()
})
}
function importJSON (done) {
if (!done) done = () => {}
const importFiles = Array.from(document.getElementById('import-file').files)
const jsonFiles = importFiles.filter((file) => file.type === 'application/json')
importFiles.forEach((file) => {
console.log(file.name, file.type)
})
const reader = new FileReader()
reader.onerror = (e) => {
return cb(e)
}
reader.onload = (e) => {
let jsonData
try {
jsonData = JSON.parse(e.target.result)
} catch (e) {
return cb(e)
}
document.getElementById('import-file').value = null
return db.bulkDocs(jsonData.map((item) => {
delete item.doc._rev
return item.doc
}))
}
reader.readAsText(jsonFiles[0], 'UTF-8')
}
function deleteData (done) {
if (!done) done = () => {}
let count = 0
db.allDocs({include_docs: true, descending: true}, function (err, docs) {
for (let i = 0; i < docs.rows.length; i++) {
db.remove(docs.rows[i].doc, (err) => {
if (err) return done(err)
count++
if (count === docs.rows.length) return done(null)
})
}
})
}