Skip to content

Instantly share code, notes, and snippets.

@matthewstokeley
Last active April 7, 2020 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewstokeley/634b49a3086943eb4bcaab6da6340f3a to your computer and use it in GitHub Desktop.
Save matthewstokeley/634b49a3086943eb4bcaab6da6340f3a to your computer and use it in GitHub Desktop.
persistence layer integration
/*_________________________________________________________
*
* @version 0.0.2
*/
( function( $ ) {
const KEY = 'template-name'
const HTML_KEY = 'html'
const CONTAINER = '.container'
const WP_API_PATH = ''
let html;
const request = ( function request( ) {
let config = {
method: 'GET'
}
let res = fetch( WP_API_PATH, config )
let onerr = function onerr( err ) { }
return {
send: ( onresponse ) => res.then( onresponse ).catch( onerr )
}
} )( )
const store = ( function store() {
return {
get: ( key ) => localStorage.getItem( key )
set: ( val ) => localStorage.setItem( KEY, JSON.stringify( val ) )
keyExists: ( key ) => localStorage.getItem( key )
? true
: false
}
} )( )
const cookie = ( function() {
return {
get: ( name ) => cookies.get( { name: name } )
set: ( obj ) => cookies.set( obj )
exists: ( name ) => {}
}
} )( )
let onresponse = function onresponse() {
return function( res ) {
store.set( KEY, res[ HTML_KEY ] )
html = res[ HTML_KEY ]
}
}
let extend = function( fn, middleware ) {
if ( ! middleware ) {
throw new Error( 'Bad Function Call' )
}
if ( ! Array.isArray( middleware ) ) {
throw new Error(' Invalid Argument Type ')
}
return ( res ) => {
for ( let i = 0; i < middleware.length; i++ ) {
middleware[ i ].call(this, ...args )
}
cb.call( this, res )
}
}
( function() {
if ( ! cookie.exists( KEY ) ) {
let noCookieResponse = extend( onresponse, [ ( res ) => {
return ( res ) => {
cookie.set( KEY, res[ HTML_KEY ] )
}
} ] )
request.send( noCookieResponse )
}
if ( ! store.keyExists( KEY ) ) {
request.send( onresponse )
}
html = store.get( KEY )
} )( )
let container = document.querySelector( CONTAINER )
// @todo implement eventual consistency
container.innerHTML = html
} )( jQuery )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment