const express = require("express");
const app = express();
const fs = require("fs");
const path = require("path");
app.get("/:key", (req, res) => {
const key = req.params.key;
const filePath = path.join(__dirname, "db.json");
fs.readFile(filePath, (err, data) => {
if (err) {
console.error("Error reading file:", err);
return res.status(500).json({ error: "Internal server error" });
}
let jsonData;
try {
jsonData = JSON.parse(data);
} catch (err) {
console.error("Error parsing JSON:", err);
return res.status(500).json({ error: "Internal server error" });
}
if (!jsonData[key]) {
console.error("Key not found in JSON data:", key);
return res.status(404).json({ error: `Key "${key}" not found in data` });
}
res.json(jsonData[key]);
});
});
app.get("/:key/:id", (req, res) => {
const key = req.params.key;
const id = req.params.id;
const filePath = path.join(__dirname, "db.json");
fs.readFile(filePath, (err, data) => {
if (err) {
console.error(`Error reading file from disk: ${err}`);
return res.status(500).send(`Error reading file from disk: ${err}`);
}
let jsonData;
try {
jsonData = JSON.parse(data);
} catch (parseErr) {
console.error(`Error parsing JSON file: ${parseErr}`);
return res.status(500).send(`Error parsing JSON file: ${parseErr}`);
}
if (!jsonData[key]) {
console.error(`Key "${key}" not found in the JSON data.`);
return res.status(404).send(`Key "${key}" not found in the JSON data.`);
}
const item = jsonData[key].find((item) => item.id === parseInt(id));
if (!item) {
console.error(`Item with id "${id}" not found in the key "${key}".`);
return res
.status(404)
.send(`Item with id "${id}" not found in the key "${key}".`);
}
res.json(item);
});
});
app.listen(3000, () => {
console.log("Server started on port 3000");
});