Tuesday, October 25, 2022

Using local JSON file without database in Node.js

 //

////////////////////////////////////////////////////////
// JSON WITHOUT DATABASE
// //////////////////////////////////////////////////////
const fs = require('fs');
////////////////////////////////////////////////////////
const cards = JSON.parse(fs.readFileSync(`${__dirname}/data/card-data.json`));
////////////////////////////////////////////////////////
exports.checkId = (req, res, next, val) => {
if (req.params.id * 1 > cards.length) {
return res.status(404).json({
status: 'fail',
message: 'Invalid ID',
});
}
next();
};
////////////////////////////////////////////////////////
exports.getAllCards = (req, res) => {
res.status(200).json({
status: 'success',
time: req.requestTime,
result: cards.length, // if sending array!!!
data: { images: cards },
});
};
////////////////////////////////////////////////////////
exports.getCard = (req, res) => {
const id = req.params.id * 1; // convert String into Number
const card = cards.find((el) => el.id === id); // console.log(req.params);
res.status(200).json({
status: 'success',
time: req.requestTime,
data: {
card: card, // or just card instead of card: card
},
});
};
////////////////////////////////////////////////////////
exports.postCard = (req, res) => {
// solution to work without database
const newId = cards[cards.length - 1].id + 1;
const newCard = Object.assign({ id: newId }, req.body); // console.log(req.body);
cards.push(newCard);
fs.writeFile(
`${__dirname}/../data/card-data.json`,
JSON.stringify(cards),
(err) => {
res.status(201).json({
status: 'success',
data: { images: newCard },
});
}
); // use asynchronous writeFile
};
////////////////////////////////////////////////////////

//

No comments:

Post a Comment