2020-11-11 13:52:47 +02:00
|
|
|
import paginationToSql from './paginationToSql';
|
|
|
|
import { Pagination, PaginationOrder } from './types';
|
|
|
|
|
|
|
|
export interface ModelFeedPage {
|
2020-11-12 21:29:22 +02:00
|
|
|
items: any[];
|
2020-11-19 18:25:32 +02:00
|
|
|
has_more: boolean;
|
2020-11-12 21:29:22 +02:00
|
|
|
total?: number;
|
2020-11-11 13:52:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export interface WhereQuery {
|
2020-11-12 21:29:22 +02:00
|
|
|
sql: string;
|
|
|
|
params: any[];
|
2020-11-11 13:52:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Note: this method might return more fields than was requested as it will
|
|
|
|
// also return fields that are necessary for pagination.
|
2020-11-12 21:13:28 +02:00
|
|
|
export default async function(db: any, tableName: string, pagination: Pagination, whereQuery: WhereQuery = null, fields: string[] = null): Promise<ModelFeedPage> {
|
2020-11-11 13:52:47 +02:00
|
|
|
fields = fields ? fields.slice() : ['id'];
|
|
|
|
|
|
|
|
const where = whereQuery ? [whereQuery.sql] : [];
|
|
|
|
const sqlParams = whereQuery && whereQuery.params ? whereQuery.params.slice() : [];
|
|
|
|
|
|
|
|
if (!pagination.order.length) throw new Error('Pagination order must be provided');
|
|
|
|
if (pagination.order.length > 1) throw new Error('Only one pagination order field can be provided');
|
|
|
|
|
|
|
|
const paginationOrder = pagination.order[0].dir;
|
|
|
|
|
2020-11-12 21:13:28 +02:00
|
|
|
if (!pagination.order.find((o: PaginationOrder) => o.by === 'id')) {
|
2020-11-11 13:52:47 +02:00
|
|
|
pagination = {
|
|
|
|
...pagination,
|
|
|
|
order: pagination.order.concat([{
|
|
|
|
by: 'id',
|
|
|
|
dir: paginationOrder,
|
|
|
|
caseInsensitive: false,
|
|
|
|
}]),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
const orderBySql = paginationToSql(pagination);
|
|
|
|
const fieldsSql = fields.length ? db.escapeFields(fields) : '*';
|
|
|
|
const offset = (pagination.page - 1) * pagination.limit;
|
|
|
|
|
|
|
|
const sql = `
|
|
|
|
SELECT ${fieldsSql} FROM \`${tableName}\`
|
|
|
|
${where.length ? `WHERE ${where.join(' AND ')}` : ''}
|
|
|
|
ORDER BY ${orderBySql}
|
|
|
|
LIMIT ${pagination.limit}
|
|
|
|
OFFSET ${offset}
|
|
|
|
`;
|
|
|
|
|
|
|
|
// console.info('SQL', sql, sqlParams);
|
|
|
|
|
|
|
|
const rows = await db.selectAll(sql, sqlParams);
|
|
|
|
|
2020-11-19 18:25:32 +02:00
|
|
|
return {
|
|
|
|
items: rows,
|
|
|
|
has_more: rows.length >= pagination.limit,
|
|
|
|
};
|
2020-11-11 13:52:47 +02:00
|
|
|
}
|