-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
89 lines (82 loc) · 2.41 KB
/
index.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
79
80
81
82
83
84
85
86
87
88
89
const knexConstructor = require('knex');
function connect(settings) {
const knex = knexConstructor(settings);
const defaultOptions = {
dateField: 'created_at',
dbApi: knex,
limit: 1000,
offset: 0,
sortOrder: 'ASC',
};
return {
browse(table, fields, filter, options = {}) {
const dbApi = options.dbApi || defaultOptions.dbApi || knex;
const limit = options.limit || defaultOptions.limit;
const offset = options.offset || defaultOptions.offset;
const dateField = options.dateField || defaultOptions.dateField;
const sortOrder = options.sortOrder || defaultOptions.sortOrder;
let query = dbApi(table)
.where(filter)
.select(fields)
.limit(limit)
.offset(offset);
if (options.search_start_date && options.search_end_date) {
query = query
.whereBetween(dateField, [options.search_start_date, options.search_end_date]);
}
if (options.orderBy) {
if(Array.isArray(options.orderBy)) {
options.orderBy.forEach((orderBy, index) => {
if(Array.isArray(sortOrder)) {
return query = query.orderBy(orderBy, sortOrder[index]);
}
query = query.orderBy(orderBy, sortOrder);
});
} else {
query = query.orderBy(options.orderBy, sortOrder);
}
}
return query;
},
read(table, fields, filter, options = {}) {
const dbApi = options.dbApi || knex;
return dbApi(table)
.where(filter)
.select(fields)
.then(([row]) => {
return row;
});
},
add(table, fields, data, options = {}) {
const dbApi = options.dbApi || knex;
return dbApi(table)
.returning(fields)
.insert(data)
.then(([row]) => {
return row;
});
},
edit(table, fields, data, filter, options = {}) {
const dbApi = options.dbApi || knex;
return dbApi(table)
.where(filter)
.returning(fields)
.update(data)
.then(([row]) => {
return row;
});
},
del(table, filter, options = {}) {
const dbApi = options.dbApi || knex;
return dbApi(table)
.where(filter)
.del();
},
raw(sql, options = {}) {
const dbApi = options.dbApi || knex;
return dbApi.raw(sql, options)
.then(res => res.rows || res);
}
};
}
module.exports = connect;