forked from fitnr/sqlite-json
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
95 lines (75 loc) · 1.89 KB
/
index.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
87
88
89
90
91
92
93
94
95
const sqlite = require('sqlite3');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
class SqliteJson {
constructor(database) {
if (!(this instanceof SqliteJson)) {
return new SqliteJson(database);
}
this.client = database instanceof sqlite.Database
? database
: new sqlite.Database(database);
return this;
}
json(sql, options, cb) {
if (options instanceof Function) {
cb = options;
}
if (sql instanceof Object) {
options = sql;
sql = null;
}
if (!sql) {
// make sure the key is in the output
if (
options.key &&
options.columns &&
options.columns.indexOf(options.key) < 0
) {
options.columns.push(options.key);
}
const columns = options.columns ? options.columns.join(', ') : '*';
const where = options.where ? ` WHERE ${options.where}` : '';
sql = `SELECT ${columns} FROM ${options.table}${where};`;
}
this.client.all(sql, (err, data) => {
if (err) {
cb(err);
return;
}
if (options.key) {
data = data.reduce((obj, item) => {
obj[item[options.key]] = item;
return obj;
}, {});
}
cb(null, JSON.stringify(data));
});
return this;
}
save(table, filename, cb) {
this.json(table, (err, data) => {
if (err) cb(err);
mkdirp(path.dirname(filename), err => {
if (err) cb(err);
fs.writeFile(filename, data, err => {
if (err) cb(err);
else cb(null, data);
});
});
});
return this;
}
tables(cb) {
const query = "SELECT name FROM sqlite_master WHERE type='table'";
this.client.all(query, (err, tables) => {
if (err) {
cb(err);
}
cb(null, tables.map(t => t.name));
});
return this;
}
}
module.exports = SqliteJson;