2017-06-21 00:14:14 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const knex = require('../lib/knex');
|
|
|
|
|
|
|
|
async function ajaxList(params, queryFun, columns) {
|
|
|
|
return await knex.transaction(async (tx) => {
|
|
|
|
const query = queryFun(tx);
|
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
if (params.operation === 'getBy') {
|
|
|
|
query.whereIn(columns[parseInt(params.column)], params.values);
|
|
|
|
query.select(columns);
|
|
|
|
|
|
|
|
const rows = await query;
|
|
|
|
const rowsOfArray = rows.map(row => Object.keys(row).map(key => row[key]));
|
|
|
|
return rowsOfArray;
|
|
|
|
|
|
|
|
} else {
|
|
|
|
const recordsTotalQuery = query.clone().count('* as recordsTotal').first();
|
|
|
|
const recordsTotal = (await recordsTotalQuery).recordsTotal;
|
|
|
|
|
|
|
|
query.where(function() {
|
|
|
|
let searchVal = '%' + params.search.value.replace(/\\/g, '\\\\').replace(/([%_])/g, '\\$1') + '%';
|
|
|
|
for (let colIdx = 0; colIdx < params.columns.length; colIdx++) {
|
|
|
|
const col = params.columns[colIdx];
|
|
|
|
if (col.searchable) {
|
|
|
|
this.orWhere(columns[parseInt(col.data)], 'like', searchVal);
|
|
|
|
}
|
2017-06-21 00:14:14 +00:00
|
|
|
}
|
2017-07-10 15:37:56 +00:00
|
|
|
});
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
const recordsFilteredQuery = query.clone().count('* as recordsFiltered').first();
|
|
|
|
const recordsFiltered = (await recordsFilteredQuery).recordsFiltered;
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
query.offset(parseInt(params.start));
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
const limit = parseInt(params.length);
|
|
|
|
if (limit >= 0) {
|
|
|
|
query.limit(limit);
|
|
|
|
}
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
query.select(columns);
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
for (const order of params.order) {
|
|
|
|
query.orderBy(columns[params.columns[order.column].data], order.dir);
|
|
|
|
}
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-11 09:28:44 +00:00
|
|
|
query.options({rowsAsArray:true});
|
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
const rows = await query;
|
|
|
|
const rowsOfArray = rows.map(row => Object.keys(row).map(field => row[field]));
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
const result = {
|
|
|
|
draw: params.draw,
|
|
|
|
recordsTotal,
|
|
|
|
recordsFiltered,
|
|
|
|
data: rowsOfArray
|
|
|
|
};
|
2017-06-21 00:14:14 +00:00
|
|
|
|
2017-07-10 15:37:56 +00:00
|
|
|
return result;
|
|
|
|
}
|
2017-06-21 00:14:14 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
ajaxList
|
|
|
|
};
|