Untitled
unknown
javascript
2 days ago
2.8 kB
20
No Index
/* You've joined the backend team at "Acme Corp," working on a critical product catalog API. A new developer implemented a few endpoints, but we suspect there might be some underlying issues that need to be addressed before deploying to production. Your task is to review the provided Node.js (Express) code for the "Acme API." Identify at least three distinct issues related to reliability, security, or performance. For each issue, please: Describe the issue: Clearly explain what is wrong and its potential impact. Identify the likely cause: Based on your knowledge, what is causing this problem? Propose a solution: How would you fix it? Be specific about the code changes or architectural approach. Assumptions: You can assume products.json exists in the same directory as app.js. A "database" interaction is simulated using Promise.resolve or Promise.reject for simplicity. */ // app.js const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); const port = 3000; app.use(express.json()); const getProductsFromDB = () => { return new Promise((resolve, reject) => { if (Math.random() < 0.2) { reject(new Error("Database connection failed or query error!")); } else { const productsData = fs.readFileSync(path.join(__dirname, 'products.json'), 'utf8'); resolve(JSON.parse(productsData)); } }); }; const getProductByIdFromDB = (id) => { return new Promise(resolve => { const productsData = fs.readFileSync(path.join(__dirname, 'products.json'), 'utf8'); const products = JSON.parse(productsData); const product = products.find(p => p.id === parseInt(id)); resolve(product); }); }; app.get('/products', async (req, res) => { const products = await getProductsFromDB(); res.json(products); }); app.get('/product/:id', async (req, res) => { const productId = req.params.id; const product = await getProductByIdFromDB(productId); if (product) { res.json(product); } else { res.status(404).send('Product not found'); } }); app.get('/health', (req, res) => { res.status(200).send('API is healthy'); }); app.use((req, res) => { res.status(404).send('Not Found'); }); app.listen(port, () => { console.log(`Acme API listening at http://localhost:${port}`); }); // File: products.json [ { "id": 1, "name": "Acme Widget Pro", "price": 99.99, "description": "The ultimate solution for productivity." }, { "id": 2, "name": "Acme Gizmo Mini", "price": 49.50, "description": "Compact and powerful." }, { "id": 3, "name": "Acme Doodad Elite", "price": 199.00, "description": "Premium quality for discerning users." } ]
Editor is loading...
Leave a Comment