-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.js
78 lines (78 loc) · 2.09 KB
/
sql.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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sqlPool = exports.SqlPool = exports.SqlTransaction = exports.init = void 0;
const mssql = require("mssql");
// https://www.npmjs.com/package/mssql
let pool;
async function init(poolConfig) {
if (!poolConfig)
throw new Error("Missing poolConfig");
if (!pool) {
if (!poolConfig.pool)
poolConfig.pool = {
max: 30,
min: 0,
idleTimeoutMillis: 30000
};
if (!("requestTimeout" in poolConfig))
poolConfig.requestTimeout = 30000;
pool = await mssql.connect(poolConfig);
}
}
exports.init = init;
class SqlTransaction {
constructor(mssqlTransaction) {
this.transaction = mssqlTransaction;
this.open = false;
}
get mssqlTransaction() {
return this.transaction;
}
async begin(isolationLevel) {
if (!this.transaction)
throw new Error("Impossible to restart an already terminated transaction");
if (this.open)
throw new Error("Impossible to restart an ongoing transaction");
await this.transaction.begin(isolationLevel);
this.open = true;
return this;
}
async commit() {
if (!this.transaction)
throw new Error("Impossible to commit an already terminated transaction");
if (!this.open)
throw new Error("Impossible to commit a transaction that has not yet started");
await this.transaction.commit();
this.transaction = null;
}
async rollback() {
if (!this.transaction)
return;
await this.transaction.rollback();
this.transaction = null;
}
request() {
if (!this.transaction)
throw new Error("Impossible to send a request through an already terminated transaction");
if (!this.open)
throw new Error("Impossible to send a request through a transaction that has not yet started");
return this.transaction.request();
}
}
exports.SqlTransaction = SqlTransaction;
class SqlPool {
request() {
return pool.request();
}
async transaction(callback) {
const transaction = new SqlTransaction(pool.transaction());
try {
return await callback(transaction);
}
finally {
await transaction.rollback();
}
}
}
exports.SqlPool = SqlPool;
exports.sqlPool = new SqlPool();