Pagination

const getProducts = async (req: Request, res: Response) => {
    const {
        name,
        minPrice,
        maxPrice,
        minStock,
        maxStock,
        sortBy = "id",
        order = "asc",
        limit = 100,
        offset = 0,
    } = req.query;

    const filters: any = {};

    if (name) {
        filters.name = {
            contains: String(name),
        };
    }

    if (minPrice || maxPrice) {
        filters.price = {
            ...(minPrice ? { gte: Number(minPrice) } : {}),
            ...(maxPrice ? { lte: Number(maxPrice) } : {})
        };
    }

    if (minStock || maxStock) {
        filters.stock = {
            ...(minStock ? { gte: Number(minStock) } : {}),
            ...(maxStock ? { lte: Number(maxStock) } : {})
        };
    }

    try {
        const products = await prisma.product.findMany({
            where: filters,
            orderBy: { [sortBy as string]: order as "asc" | "desc" },
            take: Number(limit),
            skip: Number(offset),
        });

        if (!products) throw new Error("Get Data Error");

        res.status(200).json({
            status: "Success",
            data: products,
            message: "Get Data Success"
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: "Error",
            message: "Internal server error"
        });
    }
};

Last updated