feat: add public search pagination

This commit is contained in:
2026-09-08 19:28:13 -04:00
parent 43f4f69894
commit 27fe6c6116
6 changed files with 134 additions and 18 deletions
@@ -1,4 +1,4 @@
import { and, asc, desc, eq, ilike, or, sql } from 'drizzle-orm';
import { and, asc, count, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';
import {
inventoryItems,
@@ -56,12 +56,12 @@ export function createListingRepository(db) {
} = filters;
const conditions = [
eq(listings.status, includeSold ? 'AVAILABLE' : 'AVAILABLE'),
or(
eq(inventoryItems.status, 'ACTIVE'),
includeSold ? eq(inventoryItems.status, 'SOLD') : undefined,
inArray(
listings.status,
includeSold ? ['AVAILABLE', 'PENDING', 'CLOSED'] : ['AVAILABLE', 'PENDING'],
),
].filter(Boolean);
inArray(inventoryItems.status, includeSold ? ['ACTIVE', 'SOLD'] : ['ACTIVE']),
];
if (typeof category === 'string' && category.trim().length > 0) {
conditions.push(eq(products.categoryId, category));
@@ -97,7 +97,14 @@ export function createListingRepository(db) {
const offset = (page - 1) * limit;
const results = await db
const [countResult, results] = await Promise.all([
db
.select({ total: count() })
.from(listings)
.innerJoin(inventoryItems, eq(inventoryItems.id, listings.inventoryItemId))
.innerJoin(products, eq(products.id, inventoryItems.productId))
.where(and(...conditions)),
db
.select({ listing: listings })
.from(listings)
.innerJoin(inventoryItems, eq(inventoryItems.id, listings.inventoryItemId))
@@ -105,9 +112,13 @@ export function createListingRepository(db) {
.where(and(...conditions))
.orderBy(desc(listings.createdAt))
.limit(limit)
.offset(offset);
.offset(offset),
]);
return results.map(({ listing }) => listing);
return {
items: results.map(({ listing }) => listing),
total: Number(countResult[0]?.total ?? 0),
};
},
async updateStatus(listingId, status) {
@@ -8,7 +8,19 @@ export function createSearchService({ listingRepository }) {
return {
async searchPublic(input = {}) {
const normalized = createSearchQuery(input);
return listingRepository.searchPublic(normalized);
const result = await listingRepository.searchPublic(normalized);
const items = Array.isArray(result) ? result : result.items;
const total = Array.isArray(result) ? items.length : result.total;
return {
items,
pagination: {
page: normalized.page,
limit: normalized.limit,
total,
totalPages: Math.ceil(total / normalized.limit),
},
};
},
};
}