Hey @factoradic
I’m trying to understand the logic in the answer for this exercise.
Question: Write a route to handle PUT requests to /currencies/:name/countries
.
The :name
param represents the currency name in the currencies
object. The updated array of countries that use this currency will be sent in a query.
This route handler should replace the countries
array of the correct single-currency object with an updated array from the query. It should send the updated array as a response.
Answer:
const currencies = {
diram: {
countries: ['UAE', 'Morocco'],
},
real: {
countries: ['Brazil'],
},
dinar: {
countries: ['Algeria', 'Bahrain', 'Jordan', 'Kuwait'],
},
vatu: {
countries: ['Vanuatu'],
},
shilling: {
countries: ['Tanzania', 'Uganda', 'Somalia', 'Kenya'],
},
};
app.put('/currencies/:name/countries', (req, res, next) => {
// The name of the currency is the name parameter in our request object, and
// req.params is an object that holds properties mapped to the named route “parameters”
// Route parameters are named URL segments that are used to capture the values specified at their position in the URL
const currencyName = req.params.name;
// The new countries to update are in the body of the request object, which contains a property for each query string parameter in the route. This is what is sent in our query.
const countries = req.query;
//Access the currencies object using bracket notation
//currencies object[name sent in our request body] = list of countries sent in our query
currencies[currencyName] = countries;
//Send in the response the new updated list of countries
res.send(currencies[currencyName]);
})
If countries is our query, would an example route for this request look like this?
/currencies/:pesos/countries?=Mexico
and the request object look like this?
{
params: {
name: "pesos"
},
query: {
countries: "Mexico"
}
}