ddstats-server/libs/database/searcher.js

65 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

2021-11-01 19:08:57 +01:00
import { sqlite } from './init.js'
const entriesPerPage = process.env.ENTRIES_PER_PAGE ?? 50
export function simpleSanitize(str) {
2021-11-01 19:51:31 +01:00
return String(str).replace(/\s/g, "")
}
2021-11-01 19:08:57 +01:00
/**
* 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)}
2021-11-02 11:32:59 +01:00
${matchField ? `WHERE ${simpleSanitize(matchField)} LIKE $matchQuery` : ""}
`)
.get({
matchQuery
})['count(*)']
/ entriesPerPage
)
2021-11-01 19:08:57 +01:00
if (method === "all" && page > pageCount)
reject(`Page number too high! Page count: ${pageCount}`)
const result = sqlite
.prepare(`
2021-11-01 19:51:31 +01:00
SELECT * FROM ${simpleSanitize(table)}
2021-11-02 11:32:59 +01:00
${matchField ? `WHERE ${simpleSanitize(matchField)} LIKE $matchQuery` : ""}
2021-11-01 19:51:31 +01:00
${orderBy ? `ORDER BY ${simpleSanitize(orderBy)} ${descending === true ? "DESC" : "ASC"}` : ""}
2021-11-01 19:08:57 +01:00
${method === "all" ? `LIMIT ${entriesPerPage * (page - 1)}, ${entriesPerPage}` : ""}
`)
[method === "all" ? "all" : "get"]({
2021-11-01 19:51:31 +01:00
matchQuery
2021-11-01 19:08:57 +01:00
})
// This check should work?
if ((typeof result === "object" && !result[0]) || (!result))
reject("No search results found!")
resolve({
result,
pageCount
})
}
)
}