-
Notifications
You must be signed in to change notification settings - Fork 4
/
sql-crud-adapter.js
74 lines (68 loc) · 2.21 KB
/
sql-crud-adapter.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
function SqlCrudAdapter (queryExecutorFunction) {
function getObjects (tableName, filter, callback) {
filter = filter || [];
let where = "";
if (filter.length > 0) {
where += " WHERE " + filter.map(fi => "" + fi.name + fi.op + fi.value).join(" AND ");
}
const command = "SELECT * FROM " + tableName + where;
queryExecutorFunction(command, (error, results) => {
if (error) {
throw error;
}
callback(results.rows);
});
}
function deleteObject (tableName, idValue, callback) {
const command = "DELETE FROM " + tableName + " WHERE id='" + idValue + "'";
queryExecutorFunction(command, (error, results) => {
if (error) {
throw error;
}
callback(results);
});
}
function createObject (tableName, object, callback) {
const valueNames = [];
const valueIndexes = [];
const values = [];
Object.keys(object).forEach((key, index) => {
if (object[key] !== undefined) {
valueNames.push(key);
valueIndexes.push("$" + (index + 1));
values.push(object[key]);
}
});
const command = "INSERT INTO " + tableName + " (" + valueNames.join(", ") + ") VALUES (" + valueIndexes.join(", ") + ") RETURNING id";
queryExecutorFunction(command, values, (error, results) => {
if (error) {
throw error;
}
callback(results.rows[0].id);
});
}
function updateObject (tableName, object, callback) {
const valueNames = [];
const values = [];
Object.keys(object).forEach((key, index) => {
if (object[key] !== undefined) {
valueNames.push(key + " = $" + (index + 1));
values.push(object[key]);
}
});
const command = "UPDATE " + tableName + " SET " + valueNames.join(", ") + " WHERE id = '" + object.id + "'";
queryExecutorFunction(command, values, (error) => {
if (error) {
throw error;
}
callback(object);
});
}
return {
create: createObject,
retrieve: getObjects,
update: updateObject,
delete: deleteObject
}
}
module.exports = SqlCrudAdapter;