Skip to content

Instantly share code, notes, and snippets.

@gabrielstuff
Created February 1, 2016 11:08
Show Gist options
  • Save gabrielstuff/c3c3e1ac53d3029d3f2b to your computer and use it in GitHub Desktop.
Save gabrielstuff/c3c3e1ac53d3029d3f2b to your computer and use it in GitHub Desktop.
requirebin sketch
var superagent = require('superagent')
require('superagent-cache')()
var uri = 'http://keepcontrol.space/swanmgmt/wp-json/menu/v2/menu?slug=main'
superagent
.get(uri)
.end(function (error, response){
console.log(response.body)
}
)
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks["$"+event]=this._callbacks["$"+event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){function on(){this.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks["$"+event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks["$"+event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks["$"+event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks["$"+event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],2:[function(require,module,exports){module.exports=function(arr,fn,initial){var idx=0;var len=arr.length;var curr=arguments.length==3?initial:arr[idx++];while(idx<len){curr=fn.call(null,curr,arr[idx],++idx,arr)}return curr}},{}],superagent:[function(require,module,exports){var Emitter=require("emitter");var reduce=require("reduce");var root;if(typeof window!=="undefined"){root=window}else if(typeof self!=="undefined"){root=self}else{root=this}function noop(){}function isHost(obj){var str={}.toString.call(obj);switch(str){case"[object File]":case"[object Blob]":case"[object FormData]":return true;default:return false}}request.getXHR=function(){if(root.XMLHttpRequest&&(!root.location||"file:"!=root.location.protocol||!root.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}}return false};var trim="".trim?function(s){return s.trim()}:function(s){return s.replace(/(^\s*|\s*$)/g,"")};function isObject(obj){return obj===Object(obj)}function serialize(obj){if(!isObject(obj))return obj;var pairs=[];for(var key in obj){if(null!=obj[key]){pushEncodedKeyValuePair(pairs,key,obj[key])}}return pairs.join("&")}function pushEncodedKeyValuePair(pairs,key,val){if(Array.isArray(val)){return val.forEach(function(v){pushEncodedKeyValuePair(pairs,key,v)})}pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(val))}request.serializeObject=serialize;function parseString(str){var obj={};var pairs=str.split("&");var parts;var pair;for(var i=0,len=pairs.length;i<len;++i){pair=pairs[i];parts=pair.split("=");obj[decodeURIComponent(parts[0])]=decodeURIComponent(parts[1])}return obj}request.parseString=parseString;request.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"};request.serialize={"application/x-www-form-urlencoded":serialize,"application/json":JSON.stringify};request.parse={"application/x-www-form-urlencoded":parseString,"application/json":JSON.parse};function parseHeader(str){var lines=str.split(/\r?\n/);var fields={};var index;var line;var field;var val;lines.pop();for(var i=0,len=lines.length;i<len;++i){line=lines[i];index=line.indexOf(":");field=line.slice(0,index).toLowerCase();val=trim(line.slice(index+1));fields[field]=val}return fields}function isJSON(mime){return/[\/+]json\b/.test(mime)}function type(str){return str.split(/ *; */).shift()}function params(str){return reduce(str.split(/ *; */),function(obj,str){var parts=str.split(/ *= */),key=parts.shift(),val=parts.shift();if(key&&val)obj[key]=val;return obj},{})}function Response(req,options){options=options||{};this.req=req;this.xhr=this.req.xhr;this.text=this.req.method!="HEAD"&&(this.xhr.responseType===""||this.xhr.responseType==="text")||typeof this.xhr.responseType==="undefined"?this.xhr.responseText:null;this.statusText=this.req.xhr.statusText;this.setStatusProperties(this.xhr.status);this.header=this.headers=parseHeader(this.xhr.getAllResponseHeaders());this.header["content-type"]=this.xhr.getResponseHeader("content-type");this.setHeaderProperties(this.header);this.body=this.req.method!="HEAD"?this.parseBody(this.text?this.text:this.xhr.response):null}Response.prototype.get=function(field){return this.header[field.toLowerCase()]};Response.prototype.setHeaderProperties=function(header){var ct=this.header["content-type"]||"";this.type=type(ct);var obj=params(ct);for(var key in obj)this[key]=obj[key]};Response.prototype.parseBody=function(str){var parse=request.parse[this.type];return parse&&str&&(str.length||str instanceof Object)?parse(str):null};Response.prototype.setStatusProperties=function(status){if(status===1223){status=204}var type=status/100|0;this.status=this.statusCode=status;this.statusType=type;this.info=1==type;this.ok=2==type;this.clientError=4==type;this.serverError=5==type;this.error=4==type||5==type?this.toError():false;this.accepted=202==status;this.noContent=204==status;this.badRequest=400==status;this.unauthorized=401==status;this.notAcceptable=406==status;this.notFound=404==status;this.forbidden=403==status};Response.prototype.toError=function(){var req=this.req;var method=req.method;var url=req.url;var msg="cannot "+method+" "+url+" ("+this.status+")";var err=new Error(msg);err.status=this.status;err.method=method;err.url=url;return err};request.Response=Response;function Request(method,url){var self=this;Emitter.call(this);this._query=this._query||[];this.method=method;this.url=url;this.header={};this._header={};this.on("end",function(){var err=null;var res=null;try{res=new Response(self)}catch(e){err=new Error("Parser is unable to parse the response");err.parse=true;err.original=e;err.rawResponse=self.xhr&&self.xhr.responseText?self.xhr.responseText:null;return self.callback(err)}self.emit("response",res);if(err){return self.callback(err,res)}if(res.status>=200&&res.status<300){return self.callback(err,res)}var new_err=new Error(res.statusText||"Unsuccessful HTTP response");new_err.original=err;new_err.response=res;new_err.status=res.status;self.callback(new_err,res)})}Emitter(Request.prototype);Request.prototype.use=function(fn){fn(this);return this};Request.prototype.timeout=function(ms){this._timeout=ms;return this};Request.prototype.clearTimeout=function(){this._timeout=0;clearTimeout(this._timer);return this};Request.prototype.abort=function(){if(this.aborted)return;this.aborted=true;this.xhr.abort();this.clearTimeout();this.emit("abort");return this};Request.prototype.set=function(field,val){if(isObject(field)){for(var key in field){this.set(key,field[key])}return this}this._header[field.toLowerCase()]=val;this.header[field]=val;return this};Request.prototype.unset=function(field){delete this._header[field.toLowerCase()];delete this.header[field];return this};Request.prototype.getHeader=function(field){return this._header[field.toLowerCase()]};Request.prototype.type=function(type){this.set("Content-Type",request.types[type]||type);return this};Request.prototype.parse=function(fn){this._parser=fn;return this};Request.prototype.accept=function(type){this.set("Accept",request.types[type]||type);return this};Request.prototype.auth=function(user,pass){var str=btoa(user+":"+pass);this.set("Authorization","Basic "+str);return this};Request.prototype.query=function(val){if("string"!=typeof val)val=serialize(val);if(val)this._query.push(val);return this};Request.prototype.field=function(name,val){if(!this._formData)this._formData=new root.FormData;this._formData.append(name,val);return this};Request.prototype.attach=function(field,file,filename){if(!this._formData)this._formData=new root.FormData;this._formData.append(field,file,filename||file.name);return this};Request.prototype.send=function(data){var obj=isObject(data);var type=this.getHeader("Content-Type");if(obj&&isObject(this._data)){for(var key in data){this._data[key]=data[key]}}else if("string"==typeof data){if(!type)this.type("form");type=this.getHeader("Content-Type");if("application/x-www-form-urlencoded"==type){this._data=this._data?this._data+"&"+data:data}else{this._data=(this._data||"")+data}}else{this._data=data}if(!obj||isHost(data))return this;if(!type)this.type("json");return this};Request.prototype.callback=function(err,res){var fn=this._callback;this.clearTimeout();fn(err,res)};Request.prototype.crossDomainError=function(){var err=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");err.crossDomain=true;err.status=this.status;err.method=this.method;err.url=this.url;this.callback(err)};Request.prototype.timeoutError=function(){var timeout=this._timeout;var err=new Error("timeout of "+timeout+"ms exceeded");err.timeout=timeout;this.callback(err)};Request.prototype.withCredentials=function(){this._withCredentials=true;return this};Request.prototype.end=function(fn){var self=this;var xhr=this.xhr=request.getXHR();var query=this._query.join("&");var timeout=this._timeout;var data=this._formData||this._data;this._callback=fn||noop;xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;var status;try{status=xhr.status}catch(e){status=0}if(0==status){if(self.timedout)return self.timeoutError();if(self.aborted)return;return self.crossDomainError()}self.emit("end")};var handleProgress=function(e){if(e.total>0){e.percent=e.loaded/e.total*100}e.direction="download";self.emit("progress",e)};if(this.hasListeners("progress")){xhr.onprogress=handleProgress}try{if(xhr.upload&&this.hasListeners("progress")){xhr.upload.onprogress=handleProgress}}catch(e){}if(timeout&&!this._timer){this._timer=setTimeout(function(){self.timedout=true;self.abort()},timeout)}if(query){query=request.serializeObject(query);this.url+=~this.url.indexOf("?")?"&"+query:"?"+query}xhr.open(this.method,this.url,true);if(this._withCredentials)xhr.withCredentials=true;if("GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof data&&!isHost(data)){var contentType=this.getHeader("Content-Type");var serialize=this._parser||request.serialize[contentType?contentType.split(";")[0]:""];if(!serialize&&isJSON(contentType))serialize=request.serialize["application/json"];if(serialize)data=serialize(data)}for(var field in this.header){if(null==this.header[field])continue;xhr.setRequestHeader(field,this.header[field])}this.emit("request",this);xhr.send(typeof data!=="undefined"?data:null);return this};Request.prototype.then=function(fulfill,reject){return this.end(function(err,res){err?reject(err):fulfill(res)})};request.Request=Request;function request(method,url){if("function"==typeof url){return new Request("GET",method).end(url)}if(1==arguments.length){return new Request("GET",method)}return new Request(method,url)}request.get=function(url,data,fn){var req=request("GET",url);if("function"==typeof data)fn=data,data=null;if(data)req.query(data);if(fn)req.end(fn);return req};request.head=function(url,data,fn){var req=request("HEAD",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};function del(url,fn){var req=request("DELETE",url);if(fn)req.end(fn);return req}request["del"]=del;request["delete"]=del;request.patch=function(url,data,fn){var req=request("PATCH",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};request.post=function(url,data,fn){var req=request("POST",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};request.put=function(url,data,fn){var req=request("PUT",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};module.exports=request},{emitter:1,reduce:2}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){function cacheModule(config){var self=this;config=config||{};self.type=config.type||"cache-module";self.verbose=config.verbose||false;self.defaultExpiration=config.defaultExpiration||900;self.readOnly=config.readOnly||false;self.checkOnPreviousEmpty=typeof config.checkOnPreviousEmpty==="boolean"?config.checkOnPreviousEmpty:true;self.backgroundRefreshIntervalCheck=typeof config.backgroundRefreshIntervalCheck==="boolean"?config.backgroundRefreshIntervalCheck:true;self.backgroundRefreshInterval=config.backgroundRefreshInterval||6e4;self.backgroundRefreshMinTtl=config.backgroundRefreshMinTtl||7e4;var store=null;var storageMock=config.storageMock||false;var backgroundRefreshEnabled=false;var browser=typeof window!=="undefined";var cache={db:{},expirations:{},refreshKeys:{}};setupBrowserStorage();log(false,"Cache-module client created with the following defaults:",{type:self.type,defaultExpiration:self.defaultExpiration,verbose:self.verbose,readOnly:self.readOnly});self.get=function(key,cb){throwErrorIf(arguments.length<2,"ARGUMENT_EXCEPTION: .get() requires 2 arguments.");log(false,"get() called:",{key:key});try{var now=Date.now();var expiration=cache.expirations[key];if(expiration>now){cb(null,cache.db[key])}else{expire(key);cb(null,null)}}catch(err){cb({name:"GetException",message:err},null)}};self.mget=function(keys,cb,index){throwErrorIf(arguments.length<2,"ARGUMENT_EXCEPTION: .mget() requires 2 arguments.");log(false,".mget() called:",{keys:keys});var values={};for(var i=0;i<keys.length;i++){var key=keys[i];self.get(key,function(err,response){if(response!==null){values[key]=response}})}cb(null,values,index)};self.set=function(){throwErrorIf(arguments.length<2,"ARGUMENT_EXCEPTION: .set() requires at least 2 arguments.");var key=arguments[0];var value=arguments[1];var expiration=arguments[2]||null;var refresh=arguments.length==5?arguments[3]:null;var cb=arguments.length==5?arguments[4]:arguments[3];log(false,".set() called:",{key:key,value:value});if(!self.readOnly){try{expiration=expiration?expiration*1e3:self.defaultExpiration*1e3;var exp=expiration+Date.now();cache.expirations[key]=exp;cache.db[key]=value;if(cb)cb();if(refresh){cache.refreshKeys[key]={expiration:exp,lifeSpan:expiration,refresh:refresh};backgroundRefreshInit()}overwriteBrowserStorage()}catch(err){log(true,".set() failed for cache of type "+self.type,{name:"CacheModuleSetException",message:err})}}};self.mset=function(obj,expiration,cb){throwErrorIf(arguments.length<1,"ARGUMENT_EXCEPTION: .mset() requires at least 1 argument.");log(false,".mset() called:",{data:obj});for(key in obj){if(obj.hasOwnProperty(key)){var tempExpiration=expiration||self.defaultExpiration;var value=obj[key];if(typeof value==="object"&&value.cacheValue){tempExpiration=value.expiration||tempExpiration;value=value.cacheValue}self.set(key,value,tempExpiration)}}if(cb)cb()};self.del=function(keys,cb){throwErrorIf(arguments.length<1,"ARGUMENT_EXCEPTION: .del() requires at least 1 argument.");log(false,".del() called:",{keys:keys});if(typeof keys==="object"){for(var i=0;i<keys.length;i++){var key=keys[i];delete cache.db[key];delete cache.expirations[key];delete cache.refreshKeys[key]}if(cb)cb(null,keys.length)}else{delete cache.db[keys];delete cache.expirations[keys];delete cache.refreshKeys[keys];if(cb)cb(null,1)}overwriteBrowserStorage()};self.flush=function(cb){log(false,".flush() called");cache.db={};cache.expirations={};cache.refreshKeys={};if(cb)cb();overwriteBrowserStorage()};function setupBrowserStorage(){if(browser||storageMock){if(storageMock){store=storageMock;storageKey="cache-module-storage-mock"}else{var storageType=config.storage==="local"||config.storage==="session"?config.storage:null;store=storageType&&typeof Storage!==void 0?window[storageType+"Storage"]:false;storageKey=storageType?"cache-module-"+storageType+"-storage":null}if(store){var db=store.getItem(storageKey);try{cache=JSON.parse(db)||cache}catch(err){}}else{log(true,"Browser storage is not supported by this browser. Defaulting to an in-memory cache.")}}}function overwriteBrowserStorage(){if(browser&&store||storageMock){var db=cache;try{db=JSON.stringify(db)}catch(err){}store.setItem(storageKey,db)}}function throwErrorIf(error,message){if(error)throw new Error(message)}function expire(key){delete cache.db[key];delete cache.expirations[key];overwriteBrowserStorage()}function backgroundRefreshInit(){if(!backgroundRefreshEnabled){backgroundRefreshEnabled=true;if(self.backgroundRefreshIntervalCheck){if(self.backgroundRefreshInterval>self.backgroundRefreshMinTtl){throw new Error("BACKGROUND_REFRESH_INTERVAL_EXCEPTION: backgroundRefreshInterval cannot be greater than backgroundRefreshMinTtl.")}}setInterval(backgroundRefresh,self.backgroundRefreshInterval)}}function backgroundRefresh(){for(key in cache.refreshKeys){if(cache.refreshKeys.hasOwnProperty(key)){var data=cache.refreshKeys[key];if(data.expiration-Date.now()<self.backgroundRefreshMinTtl){data.refresh(key,function(err,response){if(!err){self.set(key,response,data.lifeSpan/1e3,data.refresh,function(){})}})}}}}function log(isError,message,data){if(self.verbose||isError){if(data)console.log(self.type+": "+message,data);else console.log(self.type+message)}}}module.exports=cacheModule},{}],2:[function(require,module,exports){var Emitter=require("emitter");var reduce=require("reduce");var root;if(typeof window!=="undefined"){root=window}else if(typeof self!=="undefined"){root=self}else{root=this}function noop(){}function isHost(obj){var str={}.toString.call(obj);switch(str){case"[object File]":case"[object Blob]":case"[object FormData]":return true;default:return false}}request.getXHR=function(){if(root.XMLHttpRequest&&(!root.location||"file:"!=root.location.protocol||!root.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}}return false};var trim="".trim?function(s){return s.trim()}:function(s){return s.replace(/(^\s*|\s*$)/g,"")};function isObject(obj){return obj===Object(obj)}function serialize(obj){if(!isObject(obj))return obj;var pairs=[];for(var key in obj){if(null!=obj[key]){pushEncodedKeyValuePair(pairs,key,obj[key])}}return pairs.join("&")}function pushEncodedKeyValuePair(pairs,key,val){if(Array.isArray(val)){return val.forEach(function(v){pushEncodedKeyValuePair(pairs,key,v)})}pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(val))}request.serializeObject=serialize;function parseString(str){var obj={};var pairs=str.split("&");var parts;var pair;for(var i=0,len=pairs.length;i<len;++i){pair=pairs[i];parts=pair.split("=");obj[decodeURIComponent(parts[0])]=decodeURIComponent(parts[1])}return obj}request.parseString=parseString;request.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"};request.serialize={"application/x-www-form-urlencoded":serialize,"application/json":JSON.stringify};request.parse={"application/x-www-form-urlencoded":parseString,"application/json":JSON.parse};function parseHeader(str){var lines=str.split(/\r?\n/);var fields={};var index;var line;var field;var val;lines.pop();for(var i=0,len=lines.length;i<len;++i){line=lines[i];index=line.indexOf(":");field=line.slice(0,index).toLowerCase();val=trim(line.slice(index+1));fields[field]=val}return fields}function isJSON(mime){return/[\/+]json\b/.test(mime)}function type(str){return str.split(/ *; */).shift()}function params(str){return reduce(str.split(/ *; */),function(obj,str){var parts=str.split(/ *= */),key=parts.shift(),val=parts.shift();if(key&&val)obj[key]=val;return obj},{})}function Response(req,options){options=options||{};this.req=req;this.xhr=this.req.xhr;this.text=this.req.method!="HEAD"&&(this.xhr.responseType===""||this.xhr.responseType==="text")||typeof this.xhr.responseType==="undefined"?this.xhr.responseText:null;this.statusText=this.req.xhr.statusText;this.setStatusProperties(this.xhr.status);this.header=this.headers=parseHeader(this.xhr.getAllResponseHeaders());this.header["content-type"]=this.xhr.getResponseHeader("content-type");this.setHeaderProperties(this.header);this.body=this.req.method!="HEAD"?this.parseBody(this.text?this.text:this.xhr.response):null}Response.prototype.get=function(field){return this.header[field.toLowerCase()]};Response.prototype.setHeaderProperties=function(header){var ct=this.header["content-type"]||"";this.type=type(ct);var obj=params(ct);for(var key in obj)this[key]=obj[key]};Response.prototype.parseBody=function(str){var parse=request.parse[this.type];return parse&&str&&(str.length||str instanceof Object)?parse(str):null};Response.prototype.setStatusProperties=function(status){if(status===1223){status=204}var type=status/100|0;this.status=this.statusCode=status;this.statusType=type;this.info=1==type;this.ok=2==type;this.clientError=4==type;this.serverError=5==type;this.error=4==type||5==type?this.toError():false;this.accepted=202==status;this.noContent=204==status;this.badRequest=400==status;this.unauthorized=401==status;this.notAcceptable=406==status;this.notFound=404==status;this.forbidden=403==status};Response.prototype.toError=function(){var req=this.req;var method=req.method;var url=req.url;var msg="cannot "+method+" "+url+" ("+this.status+")";var err=new Error(msg);err.status=this.status;err.method=method;err.url=url;return err};request.Response=Response;function Request(method,url){var self=this;Emitter.call(this);this._query=this._query||[];this.method=method;this.url=url;this.header={};this._header={};this.on("end",function(){var err=null;var res=null;try{res=new Response(self)}catch(e){err=new Error("Parser is unable to parse the response");err.parse=true;err.original=e;err.rawResponse=self.xhr&&self.xhr.responseText?self.xhr.responseText:null;return self.callback(err)}self.emit("response",res);if(err){return self.callback(err,res)}if(res.status>=200&&res.status<300){return self.callback(err,res)}var new_err=new Error(res.statusText||"Unsuccessful HTTP response");new_err.original=err;new_err.response=res;new_err.status=res.status;self.callback(new_err,res)})}Emitter(Request.prototype);Request.prototype.use=function(fn){fn(this);return this};Request.prototype.timeout=function(ms){this._timeout=ms;return this};Request.prototype.clearTimeout=function(){this._timeout=0;clearTimeout(this._timer);return this};Request.prototype.abort=function(){if(this.aborted)return;this.aborted=true;this.xhr.abort();this.clearTimeout();this.emit("abort");return this};Request.prototype.set=function(field,val){if(isObject(field)){for(var key in field){this.set(key,field[key])}return this}this._header[field.toLowerCase()]=val;this.header[field]=val;return this};Request.prototype.unset=function(field){delete this._header[field.toLowerCase()];delete this.header[field];return this};Request.prototype.getHeader=function(field){return this._header[field.toLowerCase()]};Request.prototype.type=function(type){this.set("Content-Type",request.types[type]||type);return this};Request.prototype.parse=function(fn){this._parser=fn;return this};Request.prototype.accept=function(type){this.set("Accept",request.types[type]||type);return this};Request.prototype.auth=function(user,pass){var str=btoa(user+":"+pass);this.set("Authorization","Basic "+str);return this};Request.prototype.query=function(val){if("string"!=typeof val)val=serialize(val);if(val)this._query.push(val);return this};Request.prototype.field=function(name,val){if(!this._formData)this._formData=new root.FormData;this._formData.append(name,val);return this};Request.prototype.attach=function(field,file,filename){if(!this._formData)this._formData=new root.FormData;this._formData.append(field,file,filename);return this};Request.prototype.send=function(data){var obj=isObject(data);var type=this.getHeader("Content-Type");if(obj&&isObject(this._data)){for(var key in data){this._data[key]=data[key]}}else if("string"==typeof data){if(!type)this.type("form");type=this.getHeader("Content-Type");if("application/x-www-form-urlencoded"==type){this._data=this._data?this._data+"&"+data:data}else{this._data=(this._data||"")+data}}else{this._data=data}if(!obj||isHost(data))return this;if(!type)this.type("json");return this};Request.prototype.callback=function(err,res){var fn=this._callback;this.clearTimeout();fn(err,res)};Request.prototype.crossDomainError=function(){var err=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");err.crossDomain=true;err.status=this.status;err.method=this.method;err.url=this.url;this.callback(err)};Request.prototype.timeoutError=function(){var timeout=this._timeout;var err=new Error("timeout of "+timeout+"ms exceeded");err.timeout=timeout;this.callback(err)};Request.prototype.withCredentials=function(){this._withCredentials=true;return this};Request.prototype.end=function(fn){var self=this;var xhr=this.xhr=request.getXHR();var query=this._query.join("&");var timeout=this._timeout;var data=this._formData||this._data;this._callback=fn||noop;xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;var status;try{status=xhr.status}catch(e){status=0}if(0==status){if(self.timedout)return self.timeoutError();if(self.aborted)return;return self.crossDomainError()}self.emit("end")};var handleProgress=function(e){if(e.total>0){e.percent=e.loaded/e.total*100}self.emit("progress",e)};if(this.hasListeners("progress")){xhr.onprogress=handleProgress}try{if(xhr.upload&&this.hasListeners("progress")){xhr.upload.onprogress=handleProgress}}catch(e){}if(timeout&&!this._timer){this._timer=setTimeout(function(){self.timedout=true;self.abort()},timeout)}if(query){query=request.serializeObject(query);this.url+=~this.url.indexOf("?")?"&"+query:"?"+query}xhr.open(this.method,this.url,true);if(this._withCredentials)xhr.withCredentials=true;if("GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof data&&!isHost(data)){var contentType=this.getHeader("Content-Type");var serialize=this._parser||request.serialize[contentType?contentType.split(";")[0]:""];if(!serialize&&isJSON(contentType))serialize=request.serialize["application/json"];if(serialize)data=serialize(data)}for(var field in this.header){if(null==this.header[field])continue;xhr.setRequestHeader(field,this.header[field])}this.emit("request",this);xhr.send(typeof data!=="undefined"?data:null);return this};Request.prototype.then=function(fulfill,reject){return this.end(function(err,res){err?reject(err):fulfill(res)})};request.Request=Request;function request(method,url){if("function"==typeof url){return new Request("GET",method).end(url)}if(1==arguments.length){return new Request("GET",method)}return new Request(method,url)}request.get=function(url,data,fn){var req=request("GET",url);if("function"==typeof data)fn=data,data=null;if(data)req.query(data);if(fn)req.end(fn);return req};request.head=function(url,data,fn){var req=request("HEAD",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};function del(url,fn){var req=request("DELETE",url);if(fn)req.end(fn);return req}request.del=del;request.delete=del;request.patch=function(url,data,fn){var req=request("PATCH",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};request.post=function(url,data,fn){var req=request("POST",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};request.put=function(url,data,fn){var req=request("PUT",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};module.exports=request},{emitter:3,reduce:4}],3:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],4:[function(require,module,exports){module.exports=function(arr,fn,initial){var idx=0;var len=arr.length;var curr=arguments.length==3?initial:arr[idx++];while(idx<len){curr=fn.call(null,curr,arr[idx],++idx,arr)}return curr}},{}],"superagent-cache":[function(require,module,exports){module.exports=function(agent,cache,defaults){var superagent=agent?agent:require("superagent");if(!superagent.patchedBySuperagentCache){superagent.cache=cache&&cache.get?cache:new(require("cache-service-cache-module"))(cache);superagent.defaults=defaults||{};var Request=superagent.Request;var props=resetProps(superagent.defaults);var supportedMethods=["GET","HEAD","POST","PUT","DELETE"];var cacheableMethods=["GET","HEAD"];superagent.patchedBySuperagentCache=true;Request.prototype.doQuery=function(doQuery){props.doQuery=doQuery;return this};Request.prototype.pruneParams=function(pruneParams){props.pruneParams=pruneParams;return this};Request.prototype.pruneOptions=function(pruneOptions){props.pruneOptions=pruneOptions;return this};Request.prototype.prune=function(prune){props.prune=prune;
return this};Request.prototype.responseProp=function(responseProp){props.responseProp=responseProp;return this};Request.prototype.expiration=function(expiration){props.expiration=expiration;return this};Request.prototype.cacheWhenEmpty=function(cacheWhenEmpty){props.cacheWhenEmpty=cacheWhenEmpty;return this};Request.prototype.backgroundRefresh=function(backgroundRefresh){props.backgroundRefresh=typeof backgroundRefresh!=="undefined"?backgroundRefresh:true;return this};Request.prototype.execute=Request.prototype.end;Request.prototype._end=function(cb){props=resetProps(superagent.defaults);this.execute(cb)};Request.prototype.end=function(cb){var curProps=props;props=resetProps(superagent.defaults);if(~supportedMethods.indexOf(this.method)){var _this=this;var key=keygen(this,curProps);if(~cacheableMethods.indexOf(this.method)){superagent.cache.get(key,function(err,response){if(!err&&response){callbackExecutor(cb,err,response,key)}else{if(curProps.doQuery){_this._end(function(err,response){if(err){return callbackExecutor(cb,err,response,key)}else if(!err&&response){if(curProps.prune){response=curProps.prune(response)}else if(curProps.responseProp){response=response[curProps.responseProp]||null}else{response=gutResponse(response)}if(!isEmpty(response)||curProps.cacheWhenEmpty){var refresh=curProps.backgroundRefresh||null;if(typeof refresh=="boolean"){refresh=getBackgroundRefreshFunction(curProps)}superagent.cache.set(key,response,curProps.expiration,refresh,function(){callbackExecutor(cb,err,response,key)})}else{callbackExecutor(cb,err,response,key)}}})}else{callbackExecutor(cb,null,null,key)}}})}else{this._end(function(err,response){if(err){return callbackExecutor(cb,err,response,key)}if(!err&&response){var keyGet=key.replace('"method":"'+_this.method+'"','"method":"GET"');var keyHead=key.replace('"method":"'+_this.method+'"','"method":"HEAD"');superagent.cache.del([keyGet,keyHead],function(){callbackExecutor(cb,err,response,key)})}})}}else{this._end(function(err,response){callbackExecutor(cb,err,response,undefined)})}};Request.prototype.reset=function(){this.req=null};function keygen(req,cProps){var cleanParams=null;var cleanOptions=null;var params=getQueryParams(req);var options=getHeaderOptions(req);if(cProps.pruneParams||cProps.pruneOptions){cleanParams=cProps.pruneParams?pruneObj(cloneObject(params),cProps.pruneParams):params;cleanOptions=cProps.pruneOptions?pruneObj(cloneObject(options),cProps.pruneOptions,true):options}return JSON.stringify({nameSpace:superagent.cache.nameSpace,method:req.method,uri:req.url,params:cleanParams||params||null,options:cleanOptions||options||null})}function getQueryParams(req){if(req&&req.qs&&!isEmpty(req.qs)){return req.qs}else if(req&&req.qsRaw){return arrayToObj(req.qsRaw)}else if(req&&req.req){return stringToObj(req.req.path)}else if(req&&req._query){return stringToObj(req._query.join("&"))}return null}function getHeaderOptions(req){if(req&&req.req&&req.req._headers){return req.req._headers}else if(req&&req._header){return req._header}return null}function arrayToObj(arr){if(arr&&arr.length){var obj={};for(var i=0;i<arr.length;i++){var str=arr[i];var kvArray=str.split("&");for(var j=0;j<kvArray.length;j++){var kvString=kvArray[j].split("=");obj[kvString[0]]=kvString[1]}}return obj}return null}function stringToObj(str){if(str){var obj={};if(~str.indexOf("?")){var strs=str.split("?");str=strs[1]}var kvArray=str.split("&");for(var i=0;i<kvArray.length;i++){var kvString=kvArray[i].split("=");obj[kvString[0]]=kvString[1]}return obj}return null}function pruneObj(obj,props,isOptions){for(var i=0;i<props.length;i++){var prop=props[i];if(isOptions){prop=prop.toLowerCase()}delete obj[prop]}return obj}function gutResponse(r){var newResponse={};newResponse.body=r.body;newResponse.text=r.text;newResponse.headers=r.headers;newResponse.statusCode=r.statusCode;newResponse.status=r.status;newResponse.ok=r.ok;return newResponse}function isEmpty(val){return val===false||val===null||typeof val=="object"&&Object.keys(val).length==0}function cloneObject(obj){var newObj={};for(var attr in obj){if(obj.hasOwnProperty(attr)){newObj[attr]=obj[attr]}}return newObj}function resetProps(d){return{doQuery:typeof d.doQuery==="boolean"?d.doQuery:true,cacheWhenEmpty:typeof d.cacheWhenEmpty==="boolean"?d.cacheWhenEmpty:true,prune:d.prune,pruneParams:d.pruneParams,pruneOptions:d.pruneOptions,responseProp:d.responseProp,expiration:d.expiration,backgroundRefresh:d.backgroundRefresh}}function getBackgroundRefreshFunction(curProps){return function(key,cb){key=JSON.parse(key);var method=key.method.toLowerCase();var request=superagent[method](key.uri).doQuery(curProps.doQuery).pruneParams(curProps.pruneParams).pruneOptions(curProps.pruneOptions).prune(curProps.prune).responseProp(curProps.responseProp).expiration(curProps.expiration).cacheWhenEmpty(curProps.cacheWhenEmpty);if(key.params){request.query(key.params)}if(key.options){request.set(key.options)}request.end(cb)}}function callbackExecutor(cb,err,response,key){if(cb.length===1){cb(response)}else if(cb.length>1){cb(err,response,key)}else{throw new Error("UnsupportedCallbackException: Your .end() callback must pass at least one argument.")}}}if(!agent){return superagent}}},{"cache-service-cache-module":1,superagent:2}]},{},[]);var superagent=require("superagent");require("superagent-cache")();var uri="http://keepcontrol.space/swanmgmt/wp-json/menu/v2/menu?slug=main";superagent.get(uri).end(function(error,response){console.log(response.body)});
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"superagent": "1.7.2",
"superagent-cache": "1.3.2"
}
}
<!-- contents of this file will be placed inside the <body> -->
hello
<!-- contents of this file will be placed inside the <head> -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment