In my current function, I am making a request to fetch data and storing it as an object (OBJ).
Afterwards, I make another request to get a new URL that requires me to update the URL with values from the stored data.
The information saved in the object is as follows:
{
"location": {
"ip": "78.152.221.20",
"success": true,
"type": "IPv4",
"continent": "Europe",
"continent_code": "EU",
"country": "Ireland",
"country_code": "IE",
"country_flag": "https://cdn.ipwhois.io/flags/ie.svg",
"country_capital": "Dublin",
"country_phone": "+353",
"country_neighbours": "GB",
"region": "County Dublin",
"city": "Swords",
"latitude": "53.4557467",
"longitude": "-6.2197406",
"asn": "AS15502",
"org": "Vodafone Ireland",
"isp": "Vodafone Ireland Limited",
"timezone": "Europe/Dublin",
"timezone_name": "Greenwich Mean Time",
"timezone_dstOffset": "0",
"timezone_gmtOffset": "0",
"timezone_gmt": "GMT 0:00",
"currency": "Euro",
"currency_code": "EUR",
"currency_symbol": "€",
"currency_rates": "0.926884",
"currency_plural": "euros",
"completed_requests": 49
}
}
The second request provides this URL which needs to be updated accordingly:
"url": "https://api.sunrise-sunset.org/json?lat={{ location.latitude }}&lng={{ location.longitude }}"
I attempted to create a function that manipulates the string and returns it. Once returned, it should be set as a string template literal like so:
`https://api.sunrise-sunset.org/json?lat=${OBJ['location']['latitude']&lng=${OBJ['location']['longitude']`
Unfortunately, this approach is not working as expected. The string is being used without taking into account the previously stored values in OBJ.
Below is the code snippet for reference. Any suggestions, pointers, or feedback would be greatly appreciated.
const interpolateURLorMessage = (string) => {
if (CONST.DEBUG) {
console.log('functions.checkURLorMessage: string:', string);
}
if (!string) {
return null;
}
if (string.includes('{{') && string.includes('}}')) {
const myRegexp = /\{{(.*?)\}}/g;
const matches = string.match(myRegexp);
let newURL = `${string}`;
matches.forEach((ele) => {
const match = ele;
let newMatch = ele.replace('.', '\'][\'');
newMatch = newMatch.replace('{{', '${OBJ[\'');
newMatch = newMatch.replace('}}', '\']');
newMatch = newMatch.replace(/\s/g, '');
newURL = newURL.replace(match, newMatch);
});
return newURL;
} else {
// Noting to interpolate
return string;
}
};