Skip to content

Instantly share code, notes, and snippets.

@janbaykara
Created July 15, 2020 16:13
Show Gist options
  • Save janbaykara/e3e33fc6872e4b98adfa48a82d82dd70 to your computer and use it in GitHub Desktop.
Save janbaykara/e3e33fc6872e4b98adfa48a82d82dd70 to your computer and use it in GitHub Desktop.
A helper minilibrary for working with Metomic consent policies
export const ensureConsentFor = async (slug: string, askAgain = true) => {
const state = await getConsentState(slug)
if (state === true) return true
if (!askAgain) return false
return await requestConsentFor(slug)
}
enum State {
CONSENTED = 'CONSENTED',
DECLINED = 'DECLINED'
}
export const getConsentState = (slug: string) => new Promise<boolean>(resolve => {
// @ts-ignore
Metomic('getConsentState', { slug }, ({ state }) => {
return resolve(state === State.CONSENTED)
})
})
export const requestConsentFor = (requestedSlug: string) => new Promise<boolean>(resolve => {
let hasChanged = false
// @ts-ignore
// Open the consent request window
Metomic('ConsentManager:requestConsentFor', {slug: requestedSlug })
// If they say yes, tell the function consumer the good news
// @ts-ignore
Metomic('ConsentManager:onConsentStateChange', ({ slug, state }) => {
if (hasChanged) return
if (slug === requestedSlug) {
hasChanged = true
}
return resolve(state === State.CONSENTED)
})
// If they say no, there's no change, and
// on window close we send the bad news to the function consumer
// @ts-ignore
Metomic('ConsentManager:onHide', async (res) => {
console.log("ON HIDE", res)
if (hasChanged) return
hasChanged = true
return resolve(await getConsentState(requestedSlug))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment