datatable query helper
This commit is contained in:
parent
31ce135b3a
commit
7ce25d324d
65
src/utils/datatable.ts
Normal file
65
src/utils/datatable.ts
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
import { db } from "@db/db";
|
||||||
|
|
||||||
|
export interface RequestQuery {
|
||||||
|
length: string;
|
||||||
|
start: string;
|
||||||
|
order: { column: string; dir: string }[];
|
||||||
|
columns: { [key: string]: { data: string; searchable: string } };
|
||||||
|
search: { value: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResponseQuery {
|
||||||
|
query: Knex.QueryBuilder;
|
||||||
|
recordsTotal: number | string;
|
||||||
|
recordsFiltered: number | string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const buildDatatableQuery = async (request: { query: RequestQuery }, tableName: string): Promise<ResponseQuery> => {
|
||||||
|
const size: number = parseInt(request.query.length) || 10;
|
||||||
|
const start: number = parseInt(request.query.start);
|
||||||
|
const order: string = (
|
||||||
|
request.query.order && request.query.columns
|
||||||
|
[request.query.order[0].column].data
|
||||||
|
) || 'id'
|
||||||
|
const direction: string = (request.query.order && request.query.order[0].dir) || "asc";
|
||||||
|
const search: string = request.query.search.value;
|
||||||
|
|
||||||
|
let query = db(tableName);
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
console.log("applying search: " + search)
|
||||||
|
console.log("columns: " + JSON.stringify(request.query.columns, null, 4));
|
||||||
|
query = query.where(builder => {
|
||||||
|
Object.values(request.query.columns)
|
||||||
|
.filter(column => column.searchable === "true")
|
||||||
|
.forEach((col, index) =>
|
||||||
|
index === 0
|
||||||
|
? builder.where(col.data, "like", `%${search}%`)
|
||||||
|
: builder.orWhere(col.data, "like", `%${search}%`)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
console.log(query.toSQL());
|
||||||
|
// Object.keys(request.query.columns).forEach(key => {
|
||||||
|
// const column = request.query.columns[key];
|
||||||
|
// console.log(JSON.stringify(column));
|
||||||
|
// if (column.searchable === "true") {
|
||||||
|
// query = query.where(column.data, "like", `%${search}%`);
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
}
|
||||||
|
|
||||||
|
const recordsTotalResult = await db(tableName).count("* as count").first();
|
||||||
|
const recordsTotal = recordsTotalResult ? recordsTotalResult.count : 0;
|
||||||
|
|
||||||
|
const recordsFilteredResult = await query.clone().count("* as count").first();
|
||||||
|
const recordsFiltered = recordsFilteredResult ? recordsFilteredResult.count : 0;
|
||||||
|
|
||||||
|
query = query.orderBy(order, direction).limit(size).offset(start);
|
||||||
|
|
||||||
|
return {
|
||||||
|
query,
|
||||||
|
recordsTotal,
|
||||||
|
recordsFiltered
|
||||||
|
};
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user