All files / src/controllers/products-controllers productsPagination.js

92.3% Statements 12/13
83.33% Branches 10/12
100% Functions 3/3
91.66% Lines 11/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32            8x 8x 8x 8x 8x 8x         8x 8x                   8x 2x   6x  
import { productDataTypes } from "../../CONSTANT/projections.js";
import createProjection from "../../utilities/createProjection.js";
import ProductsModel from "../../models/Products.js";
 
 
export default async function productsPagination(query) {
    const { page = 1, pageSize = 10, returnType, type, categories } = query;
    const skip = (page - 1) * pageSize;
    const projection = returnType ? createProjection(returnType) : productDataTypes[type ?? "basic"];
    try {
        const categoriesFilter = createCategoriesFilter(categories);
        const products = await ProductsModel.find(
            categoriesFilter ? { $or: categoriesFilter } : {},
            projection,
            { limit: +pageSize + 1, skip }
        );
        const thereIsNextPage = !!products[pageSize];
        return {
            products: products.slice(0, thereIsNextPage ? -1 : undefined),
            thereIsNextPage
        }
    } catch {
        return null
    }
}
 
function createCategoriesFilter(categories) {
    if (categories) {
        return categories.split(",").map((category) => ({ category }))
    }
    return null
}