Add public category lookup options, allowlisted sort ordering, URL-backed catalog controls, and strict search route validation with regression tests.
This commit is contained in:
@@ -14,6 +14,7 @@ import { registerAdminProductRoutes } from '../modules/products/routes/admin-pro
|
|||||||
import { registerPublicProductRoutes } from '../modules/products/routes/public-product-routes.js';
|
import { registerPublicProductRoutes } from '../modules/products/routes/public-product-routes.js';
|
||||||
import { registerPublicSearchRoutes } from '../modules/search/routes/public-search-routes.js';
|
import { registerPublicSearchRoutes } from '../modules/search/routes/public-search-routes.js';
|
||||||
import { registerPublicSellerRoutes } from '../modules/sellers/routes/public-seller-routes.js';
|
import { registerPublicSellerRoutes } from '../modules/sellers/routes/public-seller-routes.js';
|
||||||
|
import { registerPublicLookupRoutes } from '../modules/inventory/routes/public-lookup-routes.js';
|
||||||
import { registerAdminSaleRoutes } from '../modules/sales/routes/admin-sale-routes.js';
|
import { registerAdminSaleRoutes } from '../modules/sales/routes/admin-sale-routes.js';
|
||||||
import { registerAdminAcquisitionRoutes } from '../modules/acquisitions/routes/admin-acquisition-routes.js';
|
import { registerAdminAcquisitionRoutes } from '../modules/acquisitions/routes/admin-acquisition-routes.js';
|
||||||
import { registerAdminDashboardRoutes } from '../modules/dashboard/routes/admin-dashboard-routes.js';
|
import { registerAdminDashboardRoutes } from '../modules/dashboard/routes/admin-dashboard-routes.js';
|
||||||
@@ -105,6 +106,10 @@ export function buildApp(dependencies) {
|
|||||||
...dependencies,
|
...dependencies,
|
||||||
prefix: '/api/v1',
|
prefix: '/api/v1',
|
||||||
});
|
});
|
||||||
|
app.register(registerPublicLookupRoutes, {
|
||||||
|
...dependencies,
|
||||||
|
prefix: '/api/v1',
|
||||||
|
});
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export async function registerPublicLookupRoutes(app, options) {
|
||||||
|
const { catalogLookupRepository } = options;
|
||||||
|
|
||||||
|
app.get('/public/lookups/categories', async () => ({
|
||||||
|
data: await catalogLookupRepository.listCategories(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ export function createListingRepository(db) {
|
|||||||
page = 1,
|
page = 1,
|
||||||
limit = 20,
|
limit = 20,
|
||||||
includeSold = false,
|
includeSold = false,
|
||||||
|
sort = 'recent',
|
||||||
} = filters;
|
} = filters;
|
||||||
|
|
||||||
const conditions = [
|
const conditions = [
|
||||||
@@ -96,6 +97,11 @@ export function createListingRepository(db) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const offset = (page - 1) * limit;
|
const offset = (page - 1) * limit;
|
||||||
|
const sortOrder = sort === 'price_low'
|
||||||
|
? listings.askingPriceMinor
|
||||||
|
: sort === 'price_high'
|
||||||
|
? desc(listings.askingPriceMinor)
|
||||||
|
: desc(listings.createdAt);
|
||||||
|
|
||||||
const [countResult, results] = await Promise.all([
|
const [countResult, results] = await Promise.all([
|
||||||
db
|
db
|
||||||
@@ -110,7 +116,7 @@ export function createListingRepository(db) {
|
|||||||
.innerJoin(inventoryItems, eq(inventoryItems.id, listings.inventoryItemId))
|
.innerJoin(inventoryItems, eq(inventoryItems.id, listings.inventoryItemId))
|
||||||
.innerJoin(products, eq(products.id, inventoryItems.productId))
|
.innerJoin(products, eq(products.id, inventoryItems.productId))
|
||||||
.where(and(...conditions))
|
.where(and(...conditions))
|
||||||
.orderBy(desc(listings.createdAt))
|
.orderBy(sortOrder, desc(listings.createdAt))
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.offset(offset),
|
.offset(offset),
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export function createSearchQuery({
|
|||||||
page = 1,
|
page = 1,
|
||||||
limit = 20,
|
limit = 20,
|
||||||
includeSold = false,
|
includeSold = false,
|
||||||
|
sort = 'recent',
|
||||||
}) {
|
}) {
|
||||||
const text = normalizeSearchQuery(query);
|
const text = normalizeSearchQuery(query);
|
||||||
|
|
||||||
@@ -50,6 +51,10 @@ export function createSearchQuery({
|
|||||||
throw new Error('minPriceMinor must be <= maxPriceMinor');
|
throw new Error('minPriceMinor must be <= maxPriceMinor');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!['recent', 'price_low', 'price_high'].includes(sort)) {
|
||||||
|
throw new Error('sort must be recent, price_low, or price_high');
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
text,
|
text,
|
||||||
...(typeof category === 'string' && category.trim().length > 0 ? { category: category.trim() } : {}),
|
...(typeof category === 'string' && category.trim().length > 0 ? { category: category.trim() } : {}),
|
||||||
@@ -58,6 +63,7 @@ export function createSearchQuery({
|
|||||||
page,
|
page,
|
||||||
limit,
|
limit,
|
||||||
includeSold,
|
includeSold,
|
||||||
|
...(sort !== 'recent' ? { sort } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export async function registerPublicSearchRoutes(app, options) {
|
|||||||
page: coerceNumber(request.query.page, 'page', 1),
|
page: coerceNumber(request.query.page, 'page', 1),
|
||||||
limit: coerceNumber(request.query.limit, 'limit', 20),
|
limit: coerceNumber(request.query.limit, 'limit', 20),
|
||||||
includeSold: request.query.includeSold === 'true' || request.query.includeSold === true,
|
includeSold: request.query.includeSold === 'true' || request.query.includeSold === true,
|
||||||
|
sort: request.query.sort ?? 'recent',
|
||||||
};
|
};
|
||||||
|
|
||||||
return { data: await searchService.searchPublic(filters) };
|
return { data: await searchService.searchPublic(filters) };
|
||||||
|
|||||||
@@ -41,6 +41,11 @@ test('builds a public query filter set that hides sold items by default', () =>
|
|||||||
assert.deepEqual(filters.sort, ['recently_added']);
|
assert.deepEqual(filters.sort, ['recently_added']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('accepts only the supported public search sort values', () => {
|
||||||
|
assert.equal(createSearchQuery({ sort: 'price_low' }).sort, 'price_low');
|
||||||
|
assert.throws(() => createSearchQuery({ sort: 'random' }), /sort must be recent/);
|
||||||
|
});
|
||||||
|
|
||||||
test('normalizes whitespace and punctuation in free-text search terms', () => {
|
test('normalizes whitespace and punctuation in free-text search terms', () => {
|
||||||
assert.equal(normalizeSearchQuery(' Pikachu #199 / holo '), 'pikachu 199 holo');
|
assert.equal(normalizeSearchQuery(' Pikachu #199 / holo '), 'pikachu 199 holo');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ test('returns public search results with pagination metadata', async (testContex
|
|||||||
assert.equal(filters.page, 2);
|
assert.equal(filters.page, 2);
|
||||||
assert.equal(filters.limit, 5);
|
assert.equal(filters.limit, 5);
|
||||||
assert.equal(filters.includeSold, true);
|
assert.equal(filters.includeSold, true);
|
||||||
|
assert.equal(filters.sort, 'price_low');
|
||||||
return {
|
return {
|
||||||
items: [{ id: 'listing-1', status: 'CLOSED' }],
|
items: [{ id: 'listing-1', status: 'CLOSED' }],
|
||||||
pagination: { page: 2, limit: 5, total: 6, totalPages: 2 },
|
pagination: { page: 2, limit: 5, total: 6, totalPages: 2 },
|
||||||
@@ -21,7 +22,7 @@ test('returns public search results with pagination metadata', async (testContex
|
|||||||
|
|
||||||
const response = await app.inject({
|
const response = await app.inject({
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
url: '/api/v1/public/search?query=charizard&page=2&limit=5&includeSold=true',
|
url: '/api/v1/public/search?query=charizard&page=2&limit=5&includeSold=true&sort=price_low',
|
||||||
});
|
});
|
||||||
|
|
||||||
assert.equal(response.statusCode, 200);
|
assert.equal(response.statusCode, 200);
|
||||||
@@ -46,3 +47,16 @@ test('rejects malformed numeric search filters', async (testContext) => {
|
|||||||
assert.equal(response.statusCode, 400);
|
assert.equal(response.statusCode, 400);
|
||||||
assert.equal(response.json().error.code, 'INVALID_SEARCH_FILTER');
|
assert.equal(response.json().error.code, 'INVALID_SEARCH_FILTER');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('returns active public category options', async (testContext) => {
|
||||||
|
const app = buildApp({
|
||||||
|
catalogLookupRepository: {
|
||||||
|
async listCategories() { return [{ id: 'category-1', name: 'Trading Cards' }]; },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
testContext.after(() => app.close());
|
||||||
|
|
||||||
|
const response = await app.inject({ method: 'GET', url: '/api/v1/public/lookups/categories' });
|
||||||
|
assert.equal(response.statusCode, 200);
|
||||||
|
assert.deepEqual(response.json().data, [{ id: 'category-1', name: 'Trading Cards' }]);
|
||||||
|
});
|
||||||
@@ -2,11 +2,12 @@ import { ref, watch } from 'vue';
|
|||||||
|
|
||||||
import { searchCatalog } from '@/services/catalog-service.js';
|
import { searchCatalog } from '@/services/catalog-service.js';
|
||||||
|
|
||||||
export function useCatalogSearch({ initialQuery = '', initialCategory = '', initialMinPriceMinor, initialMaxPriceMinor, initialPage = 1 } = {}) {
|
export function useCatalogSearch({ initialQuery = '', initialCategory = '', initialMinPriceMinor, initialMaxPriceMinor, initialSort = 'recent', initialPage = 1 } = {}) {
|
||||||
const query = ref(initialQuery);
|
const query = ref(initialQuery);
|
||||||
const category = ref(initialCategory);
|
const category = ref(initialCategory);
|
||||||
const minPriceMinor = ref(initialMinPriceMinor);
|
const minPriceMinor = ref(initialMinPriceMinor);
|
||||||
const maxPriceMinor = ref(initialMaxPriceMinor);
|
const maxPriceMinor = ref(initialMaxPriceMinor);
|
||||||
|
const sort = ref(initialSort);
|
||||||
const page = ref(initialPage);
|
const page = ref(initialPage);
|
||||||
const result = ref({ items: [], pagination: { page: 1, limit: 20, total: 0, totalPages: 0 } });
|
const result = ref({ items: [], pagination: { page: 1, limit: 20, total: 0, totalPages: 0 } });
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
@@ -19,7 +20,7 @@ export function useCatalogSearch({ initialQuery = '', initialCategory = '', init
|
|||||||
error.value = null;
|
error.value = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const nextResult = await searchCatalog({ query: query.value, category: category.value, minPriceMinor: minPriceMinor.value, maxPriceMinor: maxPriceMinor.value, page: page.value });
|
const nextResult = await searchCatalog({ query: query.value, category: category.value, minPriceMinor: minPriceMinor.value, maxPriceMinor: maxPriceMinor.value, sort: sort.value, page: page.value });
|
||||||
if (currentRequestId === requestId) result.value = nextResult;
|
if (currentRequestId === requestId) result.value = nextResult;
|
||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
if (currentRequestId === requestId) error.value = requestError;
|
if (currentRequestId === requestId) error.value = requestError;
|
||||||
@@ -28,7 +29,7 @@ export function useCatalogSearch({ initialQuery = '', initialCategory = '', init
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
watch([query, category, minPriceMinor, maxPriceMinor], () => {
|
watch([query, category, minPriceMinor, maxPriceMinor, sort], () => {
|
||||||
if (page.value !== 1) page.value = 1;
|
if (page.value !== 1) page.value = 1;
|
||||||
else load();
|
else load();
|
||||||
});
|
});
|
||||||
@@ -40,5 +41,5 @@ export function useCatalogSearch({ initialQuery = '', initialCategory = '', init
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { query, category, minPriceMinor, maxPriceMinor, page, result, isLoading, error, load, goToPage };
|
return { query, category, minPriceMinor, maxPriceMinor, sort, page, result, isLoading, error, load, goToPage };
|
||||||
}
|
}
|
||||||
@@ -1,29 +1,35 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { onMounted, watch } from 'vue';
|
import { onMounted, ref, watch } from 'vue';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
|
|
||||||
import { useCatalogSearch } from '@/composables/useCatalogSearch.js';
|
import { useCatalogSearch } from '@/composables/useCatalogSearch.js';
|
||||||
|
import { listPublicCategories } from '@/services/catalog-service.js';
|
||||||
import ListingCard from '@/components/molecules/ListingCard.vue';
|
import ListingCard from '@/components/molecules/ListingCard.vue';
|
||||||
|
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { query, category, minPriceMinor, maxPriceMinor, page, result, isLoading, error, load, goToPage } = useCatalogSearch({
|
const categories = ref([]);
|
||||||
|
const { query, category, minPriceMinor, maxPriceMinor, sort, page, result, isLoading, error, load, goToPage } = useCatalogSearch({
|
||||||
initialQuery: typeof route.query.q === 'string' ? route.query.q : '',
|
initialQuery: typeof route.query.q === 'string' ? route.query.q : '',
|
||||||
initialCategory: typeof route.query.category === 'string' ? route.query.category : '',
|
initialCategory: typeof route.query.category === 'string' ? route.query.category : '',
|
||||||
initialMinPriceMinor: Number.parseInt(route.query.min, 10) || undefined,
|
initialMinPriceMinor: Number.parseInt(route.query.min, 10) || undefined,
|
||||||
initialMaxPriceMinor: Number.parseInt(route.query.max, 10) || undefined,
|
initialMaxPriceMinor: Number.parseInt(route.query.max, 10) || undefined,
|
||||||
|
initialSort: typeof route.query.sort === 'string' ? route.query.sort : 'recent',
|
||||||
initialPage: Number.parseInt(route.query.page, 10) || 1,
|
initialPage: Number.parseInt(route.query.page, 10) || 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
onMounted(load);
|
onMounted(async () => {
|
||||||
|
await Promise.all([load(), listPublicCategories().then((items) => { categories.value = items; }).catch(() => {})]);
|
||||||
|
});
|
||||||
|
|
||||||
watch([query, category, minPriceMinor, maxPriceMinor, page], ([nextQuery, nextCategory, nextMin, nextMax, nextPage]) => {
|
watch([query, category, minPriceMinor, maxPriceMinor, sort, page], ([nextQuery, nextCategory, nextMin, nextMax, nextSort, nextPage]) => {
|
||||||
router.replace({
|
router.replace({
|
||||||
query: {
|
query: {
|
||||||
...(nextQuery ? { q: nextQuery } : {}),
|
...(nextQuery ? { q: nextQuery } : {}),
|
||||||
...(nextCategory ? { category: nextCategory } : {}),
|
...(nextCategory ? { category: nextCategory } : {}),
|
||||||
...(typeof nextMin === 'number' ? { min: String(nextMin) } : {}),
|
...(typeof nextMin === 'number' ? { min: String(nextMin) } : {}),
|
||||||
...(typeof nextMax === 'number' ? { max: String(nextMax) } : {}),
|
...(typeof nextMax === 'number' ? { max: String(nextMax) } : {}),
|
||||||
|
...(nextSort !== 'recent' ? { sort: nextSort } : {}),
|
||||||
...(nextPage > 1 ? { page: String(nextPage) } : {}),
|
...(nextPage > 1 ? { page: String(nextPage) } : {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -41,9 +47,10 @@ watch([query, category, minPriceMinor, maxPriceMinor, page], ([nextQuery, nextCa
|
|||||||
<input v-model="query" type="search" placeholder="Try Charizard, 151, plush..." />
|
<input v-model="query" type="search" placeholder="Try Charizard, 151, plush..." />
|
||||||
</label>
|
</label>
|
||||||
<div class="catalog-filters">
|
<div class="catalog-filters">
|
||||||
<label>Category <input v-model="category" type="search" placeholder="Cards or plush" /></label>
|
<label>Category <select v-model="category"><option value="">All categories</option><option v-for="item in categories" :key="item.id" :value="item.id">{{ item.name }}</option></select></label>
|
||||||
<label>Min price (cents) <input v-model.number="minPriceMinor" type="number" min="0" /></label>
|
<label>Min price (cents) <input v-model.number="minPriceMinor" type="number" min="0" /></label>
|
||||||
<label>Max price (cents) <input v-model.number="maxPriceMinor" type="number" min="0" /></label>
|
<label>Max price (cents) <input v-model.number="maxPriceMinor" type="number" min="0" /></label>
|
||||||
|
<label>Sort <select v-model="sort"><option value="recent">Recently added</option><option value="price_low">Price: low to high</option><option value="price_high">Price: high to low</option></select></label>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
const apiBaseUrl = import.meta.env?.VITE_API_BASE_URL ?? '/api/v1';
|
const apiBaseUrl = import.meta.env?.VITE_API_BASE_URL ?? '/api/v1';
|
||||||
|
|
||||||
export async function searchCatalog({ query = '', category = '', minPriceMinor, maxPriceMinor, page = 1, limit = 20 } = {}) {
|
export async function searchCatalog({ query = '', category = '', minPriceMinor, maxPriceMinor, sort = 'recent', page = 1, limit = 20 } = {}) {
|
||||||
const params = new URLSearchParams({ query, page: String(page), limit: String(limit) });
|
const params = new URLSearchParams({ query, page: String(page), limit: String(limit) });
|
||||||
|
if (sort !== 'recent') params.set('sort', sort);
|
||||||
if (category) params.set('category', category);
|
if (category) params.set('category', category);
|
||||||
if (typeof minPriceMinor === 'number') params.set('minPriceMinor', String(minPriceMinor));
|
if (typeof minPriceMinor === 'number') params.set('minPriceMinor', String(minPriceMinor));
|
||||||
if (typeof maxPriceMinor === 'number') params.set('maxPriceMinor', String(maxPriceMinor));
|
if (typeof maxPriceMinor === 'number') params.set('maxPriceMinor', String(maxPriceMinor));
|
||||||
@@ -15,6 +16,12 @@ export async function searchCatalog({ query = '', category = '', minPriceMinor,
|
|||||||
return payload.data;
|
return payload.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listPublicCategories() {
|
||||||
|
const response = await fetch(`${apiBaseUrl}/public/lookups/categories`);
|
||||||
|
if (!response.ok) throw new Error('Categories are unavailable.');
|
||||||
|
return (await response.json()).data;
|
||||||
|
}
|
||||||
|
|
||||||
export async function getPublicListing(id) {
|
export async function getPublicListing(id) {
|
||||||
const response = await fetch(`${apiBaseUrl}/public/listings/${encodeURIComponent(id)}`);
|
const response = await fetch(`${apiBaseUrl}/public/listings/${encodeURIComponent(id)}`);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user