Skip to content

Instantly share code, notes, and snippets.

@matthewstokeley
Last active April 6, 2020 17:54
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/cb1a8d586a8e19403273c3329d086e98 to your computer and use it in GitHub Desktop.
Save matthewstokeley/cb1a8d586a8e19403273c3329d086e98 to your computer and use it in GitHub Desktop.
a robust application lifecycle built around the fetch web api
// quick sketch
/**
* Contextual piping
* @todo create a method to mimic a piping operator
*/
const pipe = function() {
let res
for ( let i = 0; i < this.length; i++ ) {
if ( typeof this[ i ] === 'Function' ) {
res = this[ i ].call( this, res )
}
}
}
// considered to be bad practice
// @todo binding
Array.prototype.pipe = pipe
// example implementation
this.hooks.call( this.hooks )
// utility encapsulation
const _ = {}
_.pipe = function(
arr: Array<Function>,
initialArg: ?Any,
context: Object
): Any {
if ( ! context )
context = this
let res
for ( let i = 0; i < arr.length; i++ ) {
if ( typeof arr[ i ] !== 'Function' ) {
return false
}
res = arr[ i ].call( context, res )
}
return res
}
// this is a chaining api for a piping-esque function
// fn( ()=> {} ).pipe( () => {})
const fn = function( f, arg ) {
this.res = f.call(this, arg)
this.pipe = function(fn) {
fn.call(this, this.res)
}
return this
}
interface FetchOptions {
url: String
}
var FetchWrapper = function FetchWrapper( options: FetchOptions ) {
this.url = options.url ?? 'https://google.com'
this.hooks = [
'onComponentLoad',
'preflight',
'prefetch',
'onFetch',
'onFetching',
'onConnect',
'onError',
'onComplete'
]
let _proto = FetchWrapper.prototype
let _events = {}
for ( let i = 0; i < this.hooks.length; i++ ) {
let event = this.events[ this.hooks[ i ] ]
events = this.hooks[ i ] === FetchWrapper.prototype[ this.hooks[ i ] ]
// @todo reactive object mutation
? Object.defineProperty(
_proto, {
key: event,
value: FetchWrapper.prototype[ this.hooks[ i ] ]
writeable: false
enum: false
}
)
: _events
}
}
this._events = Object.assign( _events, {
'onconnect': () => {}
} )
}
/**
*
*/
FetchWrapper.prototype.fetch = function() {
fetch( this.url, {} )
.then( () => {})
.onError( () => {})
}
/**
* @param {String} hook
* @param {Function} callback
* @param {?Number}
*/
FetchWrapper.prototype.addHook = function(
hook: String,
fn: Function,
index: ?Number ):void {
( ! index )
? this.hooks
: Array.prototype.splice.call( this.hooks, index, hook )
this._events[ hook ] = fn
}
/**
* @todo pipe
*/
FetchWrapper.prototype.run = function(): any {
return _.pipe( this.hooks )
}
FetchWrapper.prototype.setHooks = function( hooks: Array<String> ) {
this.hooks = hooks
}
FetchWrapper.prototype.getHooks = function() {
return this.hooks
}
@matthewstokeley
Copy link
Author

mixin, but without local scope

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment