Try to prevent search queries from crashing

This commit is contained in:
2020-12-28 09:44:25 -08:00
parent e86b1548fc
commit c7efe96825
+19 -2
View File
@@ -9,6 +9,22 @@ const db = ds.db()
const PER_PAGE = 100
/**
* Wrap search queries that might crash FTS5 with double quotes.
* @param {String} q - search query
* @returns {String} a search query that probably won't crash SQLite's FTS5
*/
function safeQuery(q) {
let q2 = q.trim()
if (q2.match(/[-./]/)) {
q2 = `"${q2}"`
}
if (q2.match(/\+/)) {
q2 = q2.replace(/\+/g, ' ')
}
return q2
}
module.exports.GET = async (req, res) => {
const url = urlite.parse(req.url)
const q = unescape(url.search.q)
@@ -22,8 +38,9 @@ module.exports.GET = async (req, res) => {
// Search, if we have a query.
const path = `/search?q=${url.search.q}&`
const {limit, offset} = pagination.getValuesToPaginate({ currentPage: p, perPage: PER_PAGE })
const results = await ds.search(db, q, limit, offset)
const count = await ds.searchCount(db, q)
const q2 = safeQuery(q)
const results = await ds.search(db, q2, limit, offset)
const count = await ds.searchCount(db, q2)
const totalPages = pagination.getTotalPages({ totalItems: count, perPage: PER_PAGE })
const out = await page.render('search', { path, q, p, results, count, totalPages })
return send(res, 200, out)