| await dbConnect(); | await dbConnect(); | ||||
| const pageIndex = req.query.page; | |||||
| const pageIndex = req.query.pageIndex; | |||||
| const category = req.query.category === 'All' ? '' : req.query.category; | |||||
| const filterType = req.query.filterType; | |||||
| if (pageIndex < 1) { | if (pageIndex < 1) { | ||||
| res.status(422).json({ | res.status(422).json({ | ||||
| switch (method) { | switch (method) { | ||||
| case 'GET': { | case 'GET': { | ||||
| try { | try { | ||||
| const productCount = await Product.countDocuments(); | |||||
| const productCount = await Product.find({ | |||||
| category: { $regex: category }, | |||||
| }).countDocuments(); | |||||
| if (productCount === 0) { | if (productCount === 0) { | ||||
| res.status(200).json({ | res.status(200).json({ | ||||
| message: 'There are currently no products in our database.', | message: 'There are currently no products in our database.', | ||||
| product: [], | product: [], | ||||
| productCount: 0, | productCount: 0, | ||||
| next: null, | |||||
| previous: null, | |||||
| }); | }); | ||||
| break; | break; | ||||
| } | } | ||||
| throw new Error('Page does not exist!'); | throw new Error('Page does not exist!'); | ||||
| } | } | ||||
| const product = await Product.find({}) | |||||
| const product = await Product.find({ category: { $regex: category } }) | |||||
| .skip((pageIndex - 1) * 9) | .skip((pageIndex - 1) * 9) | ||||
| .limit(9); | |||||
| .limit(9) | |||||
| .sort(filterType === 'asc' ? 'name' : '-name '); | |||||
| if (!product) { | if (!product) { | ||||
| throw new Error('There are currently no products in our database.'); | 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 were fetched successfully.', | message: 'All products from our database were fetched successfully.', | ||||
| product, | product, | ||||
| productCount, | productCount, | ||||
| next: nextUrl, | |||||
| previous: previousUrl, | |||||
| }); | }); | ||||
| } catch (error) { | } catch (error) { | ||||
| res.status(400).json({ message: error.message }); | res.status(400).json({ message: error.message }); |