gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)
Description: always response with status code and proper message const Product =…
- User
Description: always response with status code and proper message
const Product = require('../models/Product'); // Adjust the path to your Product model
const readAllProducts = async (req, res) => { try { const { category, size, priceRange, sort } = req.query; let filter = {};
// Build filter based on query parameters if (category) { filter.category = category; } if (size) { filter.sizes = size; } if (priceRange) { const [minPrice, maxPrice] = priceRange.split('-'); filter.price = { $gte: minPrice, $lte: maxPrice }; } // Set sorting let sortBy = {}; if (sort) { const sortOrder = sort.startsWith('-') ? -1 : 1; const sortField = sort.replace('-', ''); sortBy[sortField] = sortOrder; // Ascending or Descending order } // Retrieve products from database const products = await Product.find(filter).sort(sortBy); // Respond with products res.json(products); } catch (error) { console.error(error); res.status(500).json({ message: 'Server error' }); }};
Generate source code based on the description above and respond in the following JSON format ONLY: ```json { "name": "prompt_name", "schema": { "type": "string", "code": "Generated code here" } } ``` IMPORTANT: - Ensure the JSON response is error-free. - Include no additional text or explanations. Respond with the JSON object only. - Assistant
{ "name": "readAllProducts", "schema": { "type": "string", "code": "const Product = require('../models/Product'); // Adjust the path to your Product model\n\nconst readAllProducts = async (req, res) => {\n try {\n const {\n category,\n size,\n priceRange,\n sort\n } = req.query;\n let filter = {};\n\n // Build filter based on query parameters\n if (category) {\n filter.category = category;\n }\n if (size) {\n filter.sizes = size;\n }\n if (priceRange) {\n const [minPrice, maxPrice] = priceRange.split('-');\n filter.price = {\n $gte: minPrice,\n $lte: maxPrice\n };\n }\n\n // Set sorting\n let sortBy = {};\n if (sort) {\n const sortOrder = sort.startsWith('-') ? -1 : 1;\n const sortField = sort.replace('-', '');\n sortBy[sortField] = sortOrder; // Ascending or Descending order\n }\n\n // Retrieve products from database\n const products = await Product.find(filter).sort(sortBy);\n\n // Respond with products\n res.json(products);\n } catch (error) {\n console.error(error);\n res.status(500).json({\n message: 'Server error'\n });\n }\n};" } }