Bläddra i källkod

perf: pagination, filter and sort on backend

pagination
ntasicc 3 år sedan
förälder
incheckning
a377e3914e
2 ändrade filer med 72 tillägg och 17 borttagningar
  1. 66
    13
      pages/api/product/category/[categoryName].js
  2. 6
    4
      requests/products/productRequest.js

+ 66
- 13
pages/api/product/category/[categoryName].js Visa fil

const Product = require('../../../../models/product');
import dbConnect from '../../../../utils/helpers/dbHelpers';
const Product = require('../../../models/product');
import dbConnect from '../../../utils/helpers/dbHelpers';


async function handler(req, res) { async function handler(req, res) {
const { method } = req; const { method } = req;
const categoryName = req.query.categoryName;
await dbConnect(); await dbConnect();


const pageIndex = req.query.pageIndex;
const category = req.query.category === 'All' ? '' : req.query.category;
const filterType = req.query.filterType;

if (pageIndex < 1) {
res.status(422).json({
message: 'Page does not exist ',
});
return;
}

switch (method) { switch (method) {
case 'GET': { case 'GET': {
try { try {
const productsByCategory = await Product.find({
category: categoryName,
});
const productCount = await Product.find({
category: { $regex: category },
}).countDocuments();


if (!productsByCategory) {
if (productCount === 0) {
res.status(200).json({ res.status(200).json({
message:
'There are currently no products in our database for the selected category.',
productsByCategory: [],
message: 'There are currently no products in our database.',
product: [],
productCount: 0,
next: null,
previous: null,
}); });
break;
}

if ((pageIndex - 1) * 9 >= productCount) {
throw new Error('Page does not exist!');
}

const product = await Product.find({ category: { $regex: category } })
.skip((pageIndex - 1) * 9)
.limit(9)
.sort(filterType === 'asc' ? 'name' : '-name ');

if (!product) {
throw new Error('There are currently no products in our database.');
} }


const previousUrl =
pageIndex > 1
? `https://localhost:3000/api/product?pageIndex=${
parseInt(pageIndex) - 1
}`
: null;
const nextUrl =
pageIndex * 9 < productCount
? `https://localhost:3000/api/product?pageIndex=${
parseInt(pageIndex) + 1
}`
: null;

res.status(200).json({ res.status(200).json({
message:
'All products from our database for the selected category were fetched successfully.',
productsByCategory,
message: 'All products from our database were fetched successfully.',
product,
productCount,
next: nextUrl,
previous: previousUrl,
}); });
} catch (error) { } catch (error) {
res.status(400).json({ message: error.message }); res.status(400).json({ message: error.message });
} }
break; break;
} }
case 'POST': {
try {
const product = await Product.create(req.body);
res
.status(201)
.json({ message: 'Your product was created and stored!', product });
} catch (error) {
res.status(400).json({ success: false });
}
break;
}
default: default:
res.status(405).json({ message: 'Method not allowed' }); res.status(405).json({ message: 'Method not allowed' });
break; break;

+ 6
- 4
requests/products/productRequest.js Visa fil

import apiEndpoints from '../apiEndpoints';

export const getAllProducts = async (pageIndex) => {
export const getAllProducts = async ({
url,
category = 'All',
filter = 'asc',
}) => {
const response = await fetch( const response = await fetch(
`http://localhost:3000${apiEndpoints.products}?page=${pageIndex}`
`${url}&category=${category}&filterType=${filter}`
); );


const data = await response.json(); const data = await response.json();

Laddar…
Avbryt
Spara