-
Notifications
You must be signed in to change notification settings - Fork 15
/
db.ts
48 lines (40 loc) · 1.39 KB
/
db.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
import sqlite3 from "sqlite3"
type DbMethodName = "run" | "get" | "all" | "each" | "exec" | "prepare"
export interface CustomizedDB extends sqlite3.Database {
promise: (method: DbMethodName, ...args: any[]) => Promise<any>
}
/**
* Stores one database instance per fhir version
*/
const DB_INSTANCES: Record<number, CustomizedDB> = {};
function getDatabase(fhirVersion: number)
{
if (!DB_INSTANCES[fhirVersion]) {
const DB = new sqlite3.Database(
`${__dirname}/database.r${fhirVersion}.db`
);
/**
* Calls database methods and returns a promise
* @param {String} method
* @param {[*]} args
*/
Object.defineProperty(DB, "promise", {
get() {
return function(method: DbMethodName, ...args: any[]) {
return new Promise((resolve, reject) => {
args.push((error: Error, result: any) => {
if (error) {
return reject(error);
}
resolve(result);
});
(DB[method] as (...args: any[]) => any)(...args);
});
}
}
});
DB_INSTANCES[fhirVersion] = DB as CustomizedDB;
}
return DB_INSTANCES[fhirVersion];
}
export default getDatabase;