1 |
import { Sequelize } from 'sequelize'; |
2 |
import { Database as DB } from 'sqlite3'; |
3 |
import DiscordClient from './Client'; |
4 |
|
5 |
export default class Database { |
6 |
client: DiscordClient; |
7 |
dbpath: string; |
8 |
db: DB; |
9 |
sequelize: Sequelize; |
10 |
|
11 |
constructor(dbpath: string, client: DiscordClient) { |
12 |
this.client = client; |
13 |
this.dbpath = dbpath; |
14 |
|
15 |
this.sequelize = new Sequelize({ |
16 |
dialect: 'sqlite', |
17 |
storage: dbpath, |
18 |
}); |
19 |
|
20 |
this.db = new DB(dbpath, (err) => { |
21 |
if (err) { |
22 |
console.log(err); |
23 |
} |
24 |
}); |
25 |
} |
26 |
|
27 |
get(sql: string, params: any[] | Function, callback?: Function) { |
28 |
return this.db.get(sql, params, callback); |
29 |
} |
30 |
|
31 |
all(sql: string, params: any[] | Function, callback?: Function) { |
32 |
return this.db.all(sql, params, callback); |
33 |
} |
34 |
|
35 |
runAsync(sql: string, paramsOrCallback: any[] | Function = []) { |
36 |
return new Promise<void>((resolve, reject) => { |
37 |
this.db.run(sql, paramsOrCallback, err => { |
38 |
if (err) { |
39 |
reject(err); |
40 |
return; |
41 |
} |
42 |
|
43 |
resolve(); |
44 |
}); |
45 |
}); |
46 |
} |
47 |
|
48 |
getAsync(sql: string, paramsOrCallback: any[] | Function = []): Promise <any> { |
49 |
return new Promise((resolve, reject) => { |
50 |
this.db.get(sql, paramsOrCallback, (err, data) => { |
51 |
if (err) { |
52 |
reject(err); |
53 |
return; |
54 |
} |
55 |
|
56 |
resolve(data); |
57 |
}); |
58 |
}); |
59 |
} |
60 |
|
61 |
allAsync(sql: string, paramsOrCallback: any[] | Function = []): Promise <any> { |
62 |
return new Promise((resolve, reject) => { |
63 |
this.db.all(sql, paramsOrCallback, (err, data) => { |
64 |
if (err) { |
65 |
reject(err); |
66 |
return; |
67 |
} |
68 |
|
69 |
resolve(data); |
70 |
}); |
71 |
}); |
72 |
} |
73 |
|
74 |
get s(): Sequelize { |
75 |
return this.sequelize; |
76 |
} |
77 |
}; |