Home > database >  Changing json object property from inside fetch using another fetch
Changing json object property from inside fetch using another fetch

Time:04-10

I am creating a web application using the REST Countries API (link given) https://restcountries.com/.
The API gives json with the property borders, which is an array of strings giving the cca3 of the bordering countries. I would like to get the names of the countries too and so am making another request for that data. So far this is what I have come up with. But, the json returned from the first request is never changed. I don't know what is going on, if anybody could advice?

const dataAPI = 'https://restcountries.com/v3.1/'
router.get('/country/:code', (req, res, next) => {
    const code = req.params.code
    fetch(`${dataAPI}/alpha/${code}?fields=borders`)
        .then(response => response.json())
        .then(json => fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`))
        .then(response => response.json())
        .then(bordersJson => {
            fetch(`${dataAPI}/alpha/${code}`)
                .then(response => response.json())
                .then(data => {
                    data.borders = bordersJson
                    res.send(data)
                }).catch(err => next(err))
        }).catch(err => next(err))
})

CodePudding user response:

Async/await is a better approach for this case.

  const dataAPI = 'https://restcountries.com/v3.1/'
    router.get('/country/:code', async (req, res, next) => {
        try {
            const code = req.params.code;
        const borderJSON = await fetch(`${dataAPI}/alpha/${code}?fields=borders`).then(response => response.json());
        // response:  {"borders":["BGD","BTN","MMR","CHN","NPL","PAK"]}
        const codes = borderJSON.borders.join(',');
        const cca3 = await fetch(`${dataAPI}/alpha?codes=${codes}&fields=cca3,name`)).then(response => response.json());
        //  [{"name":{...},"cca3":"BGD"},{"name":{...},"cca3":"PAK"}]
        res.send(cca3);
        } catch (err) {
            next(err);
        }
    
    });

CodePudding user response:

The reason the borders property was not replaced was that the API endpoint used returns an array with one object, not the object itself. Also, I found that finding the borders separately was unnecessary.

Final Solution

router.get('/country/:code', (req, res, next) => {
    const code = req.params.code
    fetch(`${dataAPI}/alpha/${code}`)
        .then(response => response.json())
        .then(json => {
            json = json[0]
            fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`)
                .then(response => response.json())
                .then(bordersJSON => {
                    json.borders = bordersJSON
                    res.send(json)
                }).catch(err => next(err))
        }).catch(err => next(err))
})
  • Related