import { sqlite } from './init.js' const entriesPerPage = process.env.ENTRIES_PER_PAGE ?? 50 export function simpleSanitize(str) { return String(str).replace(/\s/g, "") } /** * This is a 'general' search function for the sqlite database... * * @param {string} table The table to search in. * @param {string} matchField If not 'undefined' or 'null' match 'matchQuery' in this field. * @param {string} matchQuery The value to search for in 'matchField'. * @param {string} orderBy The field of which to order by, if 'null' or 'undefined' it is whatever sqlite sees as default. * @param {boolean} descending If true: sort in ascending order instead of ascending order. * @param {string} method If set to "all" it will give all results instead of only one. * @param {number} page The function paginates; this sets the page to look for. * * @returns {Promise} Returns a promise which wither resolves with the data or rejects with an error. * * @author BurnyLlama */ export default function searcher(table, matchField=undefined, matchQuery=undefined, orderBy=undefined, descending=false, method="get", page=1) { return new Promise( (resolve, reject) => { const pageCount = method === "get" ? 0 : Math.ceil( sqlite .prepare(` SELECT count(*) FROM ${simpleSanitize(table)} ${matchField ? `WHERE ${simpleSanitize(matchField)} LIKE $matchQuery` : ""} `) .get({ matchQuery })['count(*)'] / entriesPerPage ) if (method === "all" && page > pageCount) reject(`Page number too high! Page count: ${pageCount}`) const result = sqlite .prepare(` SELECT * FROM ${simpleSanitize(table)} ${matchField ? `WHERE ${simpleSanitize(matchField)} LIKE $matchQuery` : ""} ${orderBy ? `ORDER BY ${simpleSanitize(orderBy)} ${descending === true ? "DESC" : "ASC"}` : ""} ${method === "all" ? `LIMIT ${entriesPerPage * (page - 1)}, ${entriesPerPage}` : ""} `) [method === "all" ? "all" : "get"]({ matchQuery }) // This check should work? if ((typeof result === "object" && !result[0]) || (!result)) reject("No search results found!") resolve({ result, pageCount }) } ) }