Skip to content

Instantly share code, notes, and snippets.

@sotaan
Created October 6, 2016 13:45
Show Gist options
  • Save sotaan/11d351a0a6b279bb402409d89defa026 to your computer and use it in GitHub Desktop.
Save sotaan/11d351a0a6b279bb402409d89defa026 to your computer and use it in GitHub Desktop.
proxy & cookie storage experiments (use https://github.com/franciscop/cookies.js)
cookies({ token: '42' , guestHash: 'sdjskdljskdjlkjsdUHYIUYHKJH', accountType: 'BUYER'})
var encapsulatedData = val => ({ value: val, lastAccess: new Date()})
var target = { 'token': null , 'guestHash': null, 'accountType': null }
//var authorizedKeys = Object.keys(target)
for (key in target) {
//we encapsulate the data with Date of its last access
target[key] = encapsulatedData(cookies(key))
}
var handler = {
get (target, propKey, receiver) {
//console.log(`getting ${propKey} on target. Value = ${target[propKey]}`)
//restoring the default behavior since data are encapsulated
if (!(propKey in target)) {
return undefined
}
let propData = target[propKey]
//if data was accessed more than 2 minutes ago,
//we have to refetch it from the cookie (e.g. data might have changed)
let now = new Date()
if ( Math.floor( (now - propData.lastAccess) / 60000 ) >= 2 ) {
console.log(`refetching ${propKey} cookie`)
propData.value = cookies(propKey)
propData.lastAccess = now
} else {
console.log(`reusing data for ${propKey}`)
//do nothing
}
return propData.value
},
set (target, propKey, value, receiver) {
if (!(propKey in target)) {
return false
}
target[propKey].value = cookies({ [propKey]: value })(propKey)
target[propKey].lastAccess = new Date()
return true
},
defineProperty (target, propKey, descriptor) {
//console.log('forbidden fruit my son!')
return false
}
}
//proxified storage
var proxy = new Proxy(target, handler)
console.log(target, proxy.token)
proxy.accountType = 'TEST BRUH!'
proxy.accountType = 'BUYER'
//cannot define a new property nor set a new one
proxy.toto = 'Test'
console.log(proxy.toto, proxy.accountType)
//access the data every 2 minute (proxy should perform a cookie refetching)
//then retry to access the refreshed data (proxy should reuse those refetched data)
window.setInterval(_ => console.log(proxy.toto, proxy.accountType, proxy.accountType), 120000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment