Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*_________________________________________________________
*
* @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
You can’t perform that action at this time.