import { sqlite } from './init.js' const entriesPerPage = process.env.ENTRIES_PER_PAGE ?? 50 /** * 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 : parseInt(sqlite .prepare(` SELECT count(*) FROM $table ${!matchField ?? "WHERE $matchField = $matchQuery"} `) .get({ table, matchField, matchQuery }) ) if (method === "all" && page > pageCount) reject(`Page number too high! Page count: ${pageCount}`) const result = sqlite .prepare(` SELECT * FROM $table ${!matchField ?? "WHERE $matchField = $matchQuery"} ${!orderBy ?? `"ORDER BY $orderBy" ${descending === true ? "DESC" : "ASC"}`} ${method === "all" ? `LIMIT ${entriesPerPage * (page - 1)}, ${entriesPerPage}` : ""} `) [method === "all" ? "all" : "get"]({ table, matchField, matchQuery, orderBy }) // This check should work? if ((typeof result === "object" && !result[0]) || (!result)) reject("No search results found!") resolve({ result, pageCount }) } ) }