|
|
import cookie from 'cookie'; |
|
|
import debug from './debug'; |
|
|
|
|
|
let refreshRequest = null; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export default async function refreshCountryCodeCookieGdpr( signal = undefined ) { |
|
|
const cookies = cookie.parse( document.cookie ); |
|
|
if ( cookies.country_code && cookies.region ) { |
|
|
debug( |
|
|
'refreshCountryCodeCookieGdpr: country_code ( value: "%s") and region ( value: "%s") cookies are fresh', |
|
|
cookies.country_code, |
|
|
cookies.region |
|
|
); |
|
|
return; |
|
|
} |
|
|
|
|
|
if ( refreshRequest === null ) { |
|
|
refreshRequest = requestGeoData( signal ) |
|
|
.then( ( { country_short, region } ) => { |
|
|
setCookie( 'country_code', country_short ); |
|
|
|
|
|
|
|
|
|
|
|
setCookie( 'region', region === '-' ? 'unknown' : region ); |
|
|
} ) |
|
|
.catch( ( err ) => { |
|
|
debug( 'refreshCountryCodeCookieGdpr: error: ', err ); |
|
|
|
|
|
|
|
|
if ( ! cookies.country_code ) { |
|
|
setCookie( 'country_code', 'unknown' ); |
|
|
} |
|
|
if ( ! cookies.region ) { |
|
|
setCookie( 'region', 'unknown' ); |
|
|
} |
|
|
} ) |
|
|
.finally( () => { |
|
|
refreshRequest = null; |
|
|
} ); |
|
|
} |
|
|
|
|
|
await refreshRequest; |
|
|
} |
|
|
|
|
|
async function requestGeoData( signal = undefined ) { |
|
|
|
|
|
const v = new Date().getTime(); |
|
|
const res = await fetch( 'https://public-api.wordpress.com/geo/?v=' + v, { signal } ); |
|
|
if ( ! res.ok ) { |
|
|
throw new Error( `The /geo endpoint returned an error: ${ res.status } ${ res.statusText }` ); |
|
|
} |
|
|
return await res.json(); |
|
|
} |
|
|
|
|
|
function setCookie( name, value ) { |
|
|
const maxAge = 6 * 60 * 60; |
|
|
document.cookie = cookie.serialize( name, value, { path: '/', maxAge } ); |
|
|
debug( 'refreshCountryCodeCookieGdpr: %s cookie set to %s', name, value ); |
|
|
} |
|
|
|