Created
July 5, 2020 12:49
-
-
Save ahmad-ali14/d173ac732d7b6299405f93c61e935a6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const bodyParser = require('body-parser'); | |
const app = express(); | |
app.use(bodyParser.json()) | |
const quotes = require("./quotes.json"); | |
app.get('/', function(request, response) { | |
response.send('/quotes/17 should return one quote, by id') | |
}); | |
app.get("/quotes", function(request, response){ | |
response.json(quotes); | |
}); | |
// update a single quote using qouteId | |
app.put("/quotes/:quoteId", (req, res) => { | |
/** first solution | |
** this solution is not optimised beacuse we are going through the array more than one time. | |
*/ | |
/** | |
let findQuo= quotes.find(quote=> quote.id === Number(req.params.quoteId); | |
if(!findQuo){ | |
return res.send({"error":"no quote found"}) | |
} | |
quotes.splice(quotes.indexOf(findQuo),1,req.body); | |
res.send({"success": "qoute has been updated"}) | |
*/ | |
// ====================================================================================================== // | |
/** | |
* second solution | |
** optimised solution, just go through the array only one time | |
*/ | |
let updated = false; | |
quotes.map((ele,index)=>{ | |
if(index === Number(req.params.quoteId)){ | |
quotes[index] = req.body | |
res.send({"success": "qoute has been updated"}) | |
// this get us out of map function but not out of the put function | |
return updated = true | |
} | |
}) | |
// if updated, don't send a response because we have sent it inside the map function. just get us out of the put function | |
// if we don't do this we are going to get Error: Cannot set headers after they are sent to the client | |
// this is a video I made about this error: https://www.youtube.com/watch?v=kE8Ks-KbSC0 | |
if (updated){ | |
return ; | |
} | |
// if we did not update anything return an error | |
if(!updated){ | |
res.send({"error":"no quote found"}) | |
} | |
// end of second solution | |
}) | |
app.listen(process.env.PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment