Add strict public search numeric validation and URL-backed category and price filters to the catalog UI.
This commit is contained in:
@@ -1,12 +1,15 @@
|
||||
import { createApplicationError } from '../../../shared/errors/application-error.js';
|
||||
|
||||
function coerceNumber(value, fallback) {
|
||||
function coerceNumber(value, fieldName, fallback) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(String(value), 10);
|
||||
return Number.isNaN(parsed) ? fallback : parsed;
|
||||
if (Number.isNaN(parsed) || String(parsed) !== String(value)) {
|
||||
throw createApplicationError('INVALID_SEARCH_FILTER', `${fieldName} must be an integer.`, 400);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export async function registerPublicSearchRoutes(app, options) {
|
||||
@@ -24,10 +27,10 @@ export async function registerPublicSearchRoutes(app, options) {
|
||||
const filters = {
|
||||
query: request.query.query,
|
||||
category: request.query.category,
|
||||
minPriceMinor: coerceNumber(request.query.minPriceMinor, undefined),
|
||||
maxPriceMinor: coerceNumber(request.query.maxPriceMinor, undefined),
|
||||
page: coerceNumber(request.query.page, 1),
|
||||
limit: coerceNumber(request.query.limit, 20),
|
||||
minPriceMinor: coerceNumber(request.query.minPriceMinor, 'minPriceMinor', undefined),
|
||||
maxPriceMinor: coerceNumber(request.query.maxPriceMinor, 'maxPriceMinor', undefined),
|
||||
page: coerceNumber(request.query.page, 'page', 1),
|
||||
limit: coerceNumber(request.query.limit, 'limit', 20),
|
||||
includeSold: request.query.includeSold === 'true' || request.query.includeSold === true,
|
||||
};
|
||||
|
||||
|
||||
@@ -32,4 +32,17 @@ test('returns public search results with pagination metadata', async (testContex
|
||||
totalPages: 2,
|
||||
});
|
||||
assert.equal(response.json().data.items[0].id, 'listing-1');
|
||||
});
|
||||
|
||||
test('rejects malformed numeric search filters', async (testContext) => {
|
||||
const app = buildApp({ searchService: { async searchPublic() { throw new Error('should not run'); } } });
|
||||
testContext.after(() => app.close());
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/public/search?minPriceMinor=12.5',
|
||||
});
|
||||
|
||||
assert.equal(response.statusCode, 400);
|
||||
assert.equal(response.json().error.code, 'INVALID_SEARCH_FILTER');
|
||||
});
|
||||
Reference in New Issue
Block a user