-
Notifications
You must be signed in to change notification settings - Fork 0
/
NDBSqLite.ts
59 lines (53 loc) · 1.7 KB
/
NDBSqLite.ts
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
import {Database} from "sqlite3";
import * as fs from "fs";
interface NDBSqLiteConstructorOptions {
filePath: string
}
export class NDBSqLite {
private filePath: string;
private db: Database;
constructor(options: NDBSqLiteConstructorOptions) {
this.filePath = options.filePath;
}
private connect() {
const db = new Database(this.filePath);
return db;
}
public init(pathToSchema?: string) {
return new Promise<Database>((resolve, reject) => {
this.db = this.connect();
this.db.get("PRAGMA foreign_keys = ON", (err, row)=>{
if (err) {
return console.error(err.message);
}
this.db.get("PRAGMA foreign_keys", (err, row: any)=>{
if (err) {
reject();
return console.error(err.message);
}
if (pathToSchema) {
this.loadInitialSchema(pathToSchema).then(()=>{
resolve(this.db);
}, (err)=> {
reject(err);
})
} else {
resolve(this.db);
}
});
});
})
}
public loadInitialSchema(pathToSchema: string) {
return new Promise<void>((resolve, reject) => {
const sql = fs.readFileSync(pathToSchema).toString();
return this.db.exec(sql, (err:Error)=> {
if (err) {
reject(err)
} else {
resolve()
}
});
})
}
}