Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { numItems, cursor: cursorString } = paginationOpts;
- const numItemsToFetch = numItems + 1;
- let query = ctx.db.query("products");
- const sortFieldMapping = {
- "by_price": "currentPrice",
- "by_popularity": "likes",
- "by_date": "updateTime" // Corrected to match the schema field name
- };
- const sortFieldJsName = sortFieldMapping[sort.field];
- if (cursorString) {
- try {
- const parsedCursor = JSON.parse(cursorString) as { cursorValue: any; cursorId: Id<"products"> };
- const { cursorValue, cursorId } = parsedCursor;
- if (cursorValue === undefined || !cursorId) {
- // Log and proceed without cursor if it's malformed
- console.warn("Invalid cursor structure received:", cursorString);
- } else {
- query = query.filter(q => {
- // The type assertion `as any` is used because sortFieldJsName is dynamic.
- // Ensure `cursorValue` type matches the field's type.
- const docSortValue = q.field(sortFieldJsName as any);
- const docId = q.field("_id");
- if (sort.direction === "asc") {
- return q.or(
- q.gt(docSortValue, cursorValue),
- q.and(q.eq(docSortValue, cursorValue), q.gt(docId, cursorId))
- );
- } else { // desc
- return q.or(
- q.lt(docSortValue, cursorValue),
- q.and(q.eq(docSortValue, cursorValue), q.lt(docId, cursorId))
- );
- }
- });
- }
- } catch (e) {
- console.error("Failed to parse cursor string, fetching first page:", cursorString, e);
- // Invalid cursor string, effectively ignore it and fetch the first page.
- }
- }
- // dbProducts will hold raw product data from the database query
- const dbProducts: any[] = await query.take(numItemsToFetch);
- const hasMore = dbProducts.length > numItems;
- const pageProducts = hasMore ? dbProducts.slice(0, numItems) : dbProducts;
- let newContinueCursor: string | null = null;
- if (hasMore) {
- const lastProductOnPage = pageProducts[pageProducts.length - 1];
- if (lastProductOnPage) {
- // Accessing field dynamically. Ensure Product type has these fields or handle potential undefined.
- const sortVal = (lastProductOnPage as any)[sortFieldJsName];
- if (sortVal === undefined) {
- console.warn(`Sort field '${sortFieldJsName}' is undefined for product '${lastProductOnPage._id}'. Cursor may be incorrect.`);
- }
- newContinueCursor = JSON.stringify({
- cursorValue: sortVal,
- cursorId: lastProductOnPage._id
- });
- }
- }
- return {
- page: pageProducts,
- isDone: !hasMore,
- continueCursor: newContinueCursor || "",
- };
Advertisement
Add Comment
Please, Sign In to add comment