auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

pagination.js (2010B)


      1 import { HttpError } from './http/http-error.js';
      2 
      3 const DEFAULT_LIMIT = 25;
      4 const MAX_LIMIT = 100;
      5 const MAX_SEARCH_LENGTH = 128;
      6 const SEARCH_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)?$/;
      7 
      8 function invalidRequest(message) {
      9   return new HttpError(400, 'invalid_request', message);
     10 }
     11 
     12 export function parsePagination(query = {}) {
     13   let limit = DEFAULT_LIMIT;
     14   if (query.limit !== undefined) {
     15     limit = Number(query.limit);
     16     if (!Number.isInteger(limit) || limit < 1) {
     17       throw invalidRequest('limit must be a positive integer');
     18     }
     19     if (limit > MAX_LIMIT) limit = MAX_LIMIT;
     20   }
     21 
     22   let offset = 0;
     23   if (query.offset !== undefined) {
     24     offset = Number(query.offset);
     25     if (!Number.isInteger(offset) || offset < 0) {
     26       throw invalidRequest('offset must be a non-negative integer');
     27     }
     28   }
     29 
     30   let q = null;
     31   if (query.q !== undefined) {
     32     q = String(query.q).trim();
     33     if (q.length > MAX_SEARCH_LENGTH) {
     34       throw invalidRequest(`q must be at most ${MAX_SEARCH_LENGTH} characters`);
     35     }
     36     if (!q) q = null;
     37   }
     38 
     39   return { limit, offset, q };
     40 }
     41 
     42 export function pagedResult(resourceKey, rows, { limit, offset, total }) {
     43   return {
     44     [resourceKey]: rows,
     45     page: { limit, offset, total },
     46   };
     47 }
     48 
     49 export function escapeLikeTerm(term) {
     50   return String(term).replace(/[\\%_]/g, (char) => `\\${char}`);
     51 }
     52 
     53 // Column names come from caller-owned whitelists, never request input; the
     54 // identifier guard keeps that contract enforced at runtime.
     55 export function searchClause(term, columns, param = 'search') {
     56   if (!Array.isArray(columns) || columns.length === 0) {
     57     throw new Error('searchClause requires at least one column');
     58   }
     59   const conditions = columns.map((column) => {
     60     if (!SEARCH_COLUMN.test(column)) {
     61       throw new Error(`invalid search column: ${column}`);
     62     }
     63     return `${column} LIKE {${param}} ESCAPE '\\'`;
     64   });
     65   return {
     66     clause: `(${conditions.join(' OR ')})`,
     67     params: { [param]: `%${escapeLikeTerm(term)}%` },
     68   };
     69 }