I’m working on a simple App using React and express server(to learn React Redux)
So I’ve created a simple Express server app in order to return JSON with products data. And I’m not sure - should I return the whole JSON with products or filter it by category - like I’ve done it and return small part depending on users category choice?
In my small app it doesn’t matter of course. But I’m interested to know some good practices)
Here’s a code of express:
/* eslint no-console: 0 */
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const buffer = fs.readFileSync('./data.json');
const productsObj = JSON.parse(buffer);
const app = express();
app.use(cors());
app.get('/:category', (req, res) => {
const selectedProducts = productsObj.products.filter(item => item.category === req.params.category);
if (selectedProducts) {
console.log(selectedProducts[0].category);
setTimeout(() => res.json(selectedProducts), Math.floor(Math.random() * 1000));
} else {
console.log(404, req.params.category);
res.status(404).json({ error: 'category not found' });
}
});
console.log(`Starting server on port 3000`);
console.log(`Generating api with products`);
app.listen(3000);