Ben Ashton
3 years ago
7 changed files with 300 additions and 37 deletions
File diff suppressed because one or more lines are too long
@ -0,0 +1,70 @@ |
|||||||
|
import { NodeAdapterError } from "./node_adapter_error.mjs"; |
||||||
|
import { QueryWrapper } from "./query_wrapper.mjs"; |
||||||
|
import { ResponseWrapper } from "./response_wrapper.mjs"; |
||||||
|
import { enableDebug, log } from "./log.mjs"; |
||||||
|
|
||||||
|
|
||||||
|
export class DatabaseWrapper { |
||||||
|
constructor(db) { |
||||||
|
this.db = db; |
||||||
|
} |
||||||
|
|
||||||
|
close() { |
||||||
|
return new Promise((resolve, reject) => { |
||||||
|
this.db.close((err) => { |
||||||
|
if (err) { |
||||||
|
reject(NodeAdapterError.from(err)); |
||||||
|
return; |
||||||
|
} |
||||||
|
resolve(); |
||||||
|
}); |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
sql(sql, ...args) { |
||||||
|
const query = new QueryWrapper(sql); |
||||||
|
|
||||||
|
if (query.isAnyOf("INSERT", "UPDATE", "DELETE")) { |
||||||
|
return this.executeRun(query, ...args); |
||||||
|
} else { |
||||||
|
return this.executeAll(query, ...args); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
executeRun(query, ...args) { |
||||||
|
return new Promise((resolve, reject) => { |
||||||
|
log(query.sql); |
||||||
|
this.db.run(query.sql, ...args, function (err) { |
||||||
|
if (err) { |
||||||
|
reject(NodeAdapterError.from(err)); |
||||||
|
return; |
||||||
|
} |
||||||
|
|
||||||
|
const result = {}; |
||||||
|
|
||||||
|
if (query.isAnyOf("INSERT")) { |
||||||
|
result.insertId = this.lastID; |
||||||
|
} |
||||||
|
|
||||||
|
if (query.isAnyOf("UPDATE", "DELETE")) { |
||||||
|
result.rowsAffected = this.changes; |
||||||
|
} |
||||||
|
|
||||||
|
resolve(ResponseWrapper.success(result)); |
||||||
|
}); |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
executeAll(query, ...args) { |
||||||
|
return new Promise((resolve, reject) => { |
||||||
|
log(query.sql); |
||||||
|
this.db.all(query.sql, ...args, function (err, rows) { |
||||||
|
if (err) { |
||||||
|
reject(NodeAdapterError.from(err)); |
||||||
|
return; |
||||||
|
} |
||||||
|
resolve(ResponseWrapper.success({rows})); |
||||||
|
}); |
||||||
|
}); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,15 @@ |
|||||||
|
export class QueryWrapper { |
||||||
|
constructor(sql) { |
||||||
|
this.sql = sql.trim(); |
||||||
|
this.operation = sql.replace(/[^a-z].*/i, "").toUpperCase(); |
||||||
|
} |
||||||
|
|
||||||
|
isAnyOf(...operations) { |
||||||
|
for (const op of operations) { |
||||||
|
if(op.toUpperCase() === this.operation) { |
||||||
|
return true; |
||||||
|
} |
||||||
|
} |
||||||
|
return false; |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,6 @@ |
|||||||
|
export const ResponseWrapper = { |
||||||
|
success: (obj = {}) => ({ |
||||||
|
success: true, |
||||||
|
...obj |
||||||
|
}) |
||||||
|
}; |
Loading…
Reference in new issue