I´m learning backend using node.js, so I´m developing a API RESTfull. I need to use PUT to update a object by id (the id as a params) in a json file. I´m using postaman to test.
This is my array:
[
{
"item": "phone",
"price": 10000,
"id": 1
},
{
"item": "tv",
"price": 20000,
"id": 2
},
{
"item": "nintendo",
"price": 2500000,
"id": 3
},
{
"item": "ipad",
"price": "500000",
"id": 4
}
]
For example I a have a local server http://127.0.0.1:8080/products/3 (the number 3 will be the item I wanna update changing the price or the name).
I started like this
app.put("/products/:id", (request, resolve) => {
const id = Number(request.params.id);
})
in a JSON file, you need to rewrite your data every time you update data
const data = require("./<fileName>.json"); // bring your json file
const fs = require("fs"); // fileModule to updata your json file
app.put("/products/:id", (request, resolve) => {
const id = Number(request.params.id);
let idx = data.findIndex(e=>e.id===id);// getting index of data by matching your id
if(!idx){
return resolve.json({message:"data not found"});
}
data[idx] = {} // your new data with id, you will get this data from request.body
fs.writeFile("./<fileName>.json",JSON.stringify(data),(err)=>{ // writing updated data in your json fil
if(err){
return resolve.json({message:err}); // if you get ant error
}
});
resolve.json(JSON.stringify(data)); // send response
})
note:this is not the synchronous way of writing JavaScript. if you like my answer don't forget to upvote and follow.