made with requirebin
Last active
February 9, 2016 10:30
-
-
Save TimBeyer/28f64ef185269b8a6058 to your computer and use it in GitHub Desktop.
requirebin sketch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var contentful = require('contentful') | |
var util = require('util') | |
var client = contentful.createClient({ | |
// This is the space ID. A space is like a project folder in Contentful terms | |
space: 'developer_bookshelf', | |
// This is the access token for this space. Normally you get both ID and the token in the Contentful web app | |
accessToken: '0b7f6x59a0' | |
}); | |
// This API call will request an entry with the specified ID from the space defined at the top, using a space-specific access token. | |
client.entry('5PeGS2SoZGSa4GuiQsigQu') | |
.then(function (entry) { | |
document.getElementById('req1').innerHTML = util.inspect(entry, {depth: null}); | |
}); | |
client.contentType('book') | |
.then(function (contentType) { | |
document.getElementById('req2').innerHTML = util.inspect(contentType, {depth: null}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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=require("./lib/axios")},{"./lib/axios":3}],2:[function(require,module,exports){"use strict";var defaults=require("./../defaults");var utils=require("./../utils");var buildURL=require("./../helpers/buildURL");var parseHeaders=require("./../helpers/parseHeaders");var transformData=require("./../helpers/transformData");var isURLSameOrigin=require("./../helpers/isURLSameOrigin");var btoa=window.btoa||require("./../helpers/btoa");module.exports=function xhrAdapter(resolve,reject,config){var data=transformData(config.data,config.headers,config.transformRequest);var requestHeaders=utils.merge(defaults.headers.common,defaults.headers[config.method]||{},config.headers||{});if(utils.isFormData(data)){delete requestHeaders["Content-Type"]}var Adapter=XMLHttpRequest||ActiveXObject;var loadEvent="onreadystatechange";var xDomain=false;if(!isURLSameOrigin(config.url)&&window.XDomainRequest){Adapter=window.XDomainRequest;loadEvent="onload";xDomain=true}if(config.auth){var username=config.auth.username||"";var password=config.auth.password||"";requestHeaders.Authorization="Basic "+btoa(username+":"+password)}var request=new Adapter("Microsoft.XMLHTTP");request.open(config.method.toUpperCase(),buildURL(config.url,config.params,config.paramsSerializer),true);request.timeout=config.timeout;request[loadEvent]=function handleReadyState(){if(request&&(request.readyState===4||xDomain)){var responseHeaders=xDomain?null:parseHeaders(request.getAllResponseHeaders());var responseData=["text",""].indexOf(config.responseType||"")!==-1?request.responseText:request.response;var response={data:transformData(responseData,responseHeaders,config.transformResponse),status:request.status,statusText:request.statusText,headers:responseHeaders,config:config};(request.status>=200&&request.status<300||xDomain&&request.responseText?resolve:reject)(response);request=null}};if(utils.isStandardBrowserEnv()){var cookies=require("./../helpers/cookies");var xsrfValue=config.withCredentials||isURLSameOrigin(config.url)?cookies.read(config.xsrfCookieName||defaults.xsrfCookieName):undefined;if(xsrfValue){requestHeaders[config.xsrfHeaderName||defaults.xsrfHeaderName]=xsrfValue}}if(!xDomain){utils.forEach(requestHeaders,function setRequestHeader(val,key){if(!data&&key.toLowerCase()==="content-type"){delete requestHeaders[key]}else{request.setRequestHeader(key,val)}})}if(config.withCredentials){request.withCredentials=true}if(config.responseType){try{request.responseType=config.responseType}catch(e){if(request.responseType!=="json"){throw e}}}if(utils.isArrayBuffer(data)){data=new DataView(data)}request.send(data)}},{"./../defaults":6,"./../helpers/btoa":8,"./../helpers/buildURL":9,"./../helpers/cookies":11,"./../helpers/isURLSameOrigin":13,"./../helpers/parseHeaders":14,"./../helpers/transformData":16,"./../utils":17}],3:[function(require,module,exports){"use strict";var defaults=require("./defaults");var utils=require("./utils");var dispatchRequest=require("./core/dispatchRequest");var InterceptorManager=require("./core/InterceptorManager");var isAbsoluteURL=require("./helpers/isAbsoluteURL");var combineURLs=require("./helpers/combineURLs");var bind=require("./helpers/bind");function Axios(defaultConfig){this.defaultConfig=utils.merge({headers:{},timeout:defaults.timeout,transformRequest:defaults.transformRequest,transformResponse:defaults.transformResponse},defaultConfig);this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios.prototype.request=function request(config){if(typeof config==="string"){config=utils.merge({url:arguments[0]},arguments[1])}config=utils.merge(this.defaultConfig,{method:"get"},config);if(config.baseURL&&!isAbsoluteURL(config.url)){config.url=combineURLs(config.baseURL,config.url)}config.withCredentials=config.withCredentials||defaults.withCredentials;var chain=[dispatchRequest,undefined];var promise=Promise.resolve(config);this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor){chain.unshift(interceptor.fulfilled,interceptor.rejected)});this.interceptors.response.forEach(function pushResponseInterceptors(interceptor){chain.push(interceptor.fulfilled,interceptor.rejected)});while(chain.length){promise=promise.then(chain.shift(),chain.shift())}return promise};var defaultInstance=new Axios;var axios=module.exports=bind(Axios.prototype.request,defaultInstance);axios.create=function create(defaultConfig){return new Axios(defaultConfig)};axios.defaults=defaults;axios.all=function all(promises){return Promise.all(promises)};axios.spread=require("./helpers/spread");axios.interceptors=defaultInstance.interceptors;utils.forEach(["delete","get","head"],function forEachMethodNoData(method){Axios.prototype[method]=function(url,config){return this.request(utils.merge(config||{},{method:method,url:url}))};axios[method]=bind(Axios.prototype[method],defaultInstance)});utils.forEach(["post","put","patch"],function forEachMethodWithData(method){Axios.prototype[method]=function(url,data,config){return this.request(utils.merge(config||{},{method:method,url:url,data:data}))};axios[method]=bind(Axios.prototype[method],defaultInstance)})},{"./core/InterceptorManager":4,"./core/dispatchRequest":5,"./defaults":6,"./helpers/bind":7,"./helpers/combineURLs":10,"./helpers/isAbsoluteURL":12,"./helpers/spread":15,"./utils":17}],4:[function(require,module,exports){"use strict";var utils=require("./../utils");function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(fulfilled,rejected){this.handlers.push({fulfilled:fulfilled,rejected:rejected});return this.handlers.length-1};InterceptorManager.prototype.eject=function eject(id){if(this.handlers[id]){this.handlers[id]=null}};InterceptorManager.prototype.forEach=function forEach(fn){utils.forEach(this.handlers,function forEachHandler(h){if(h!==null){fn(h)}})};module.exports=InterceptorManager},{"./../utils":17}],5:[function(require,module,exports){(function(process){"use strict";module.exports=function dispatchRequest(config){return new Promise(function executor(resolve,reject){try{if(typeof XMLHttpRequest!=="undefined"||typeof ActiveXObject!=="undefined"){require("../adapters/xhr")(resolve,reject,config)}else if(typeof process!=="undefined"){require("../adapters/http")(resolve,reject,config)}}catch(e){reject(e)}})}}).call(this,require("_process"))},{"../adapters/http":2,"../adapters/xhr":2,_process:19}],6:[function(require,module,exports){"use strict";var utils=require("./utils");var PROTECTION_PREFIX=/^\)\]\}',?\n/;var DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};module.exports={transformRequest:[function transformResponseJSON(data,headers){if(utils.isFormData(data)){return data}if(utils.isArrayBuffer(data)){return data}if(utils.isArrayBufferView(data)){return data.buffer}if(utils.isObject(data)&&!utils.isFile(data)&&!utils.isBlob(data)){if(!utils.isUndefined(headers)){utils.forEach(headers,function processContentTypeHeader(val,key){if(key.toLowerCase()==="content-type"){headers["Content-Type"]=val}});if(utils.isUndefined(headers["Content-Type"])){headers["Content-Type"]="application/json;charset=utf-8"}}return JSON.stringify(data)}return data}],transformResponse:[function transformResponseJSON(data){if(typeof data==="string"){data=data.replace(PROTECTION_PREFIX,"");try{data=JSON.parse(data)}catch(e){}}return data}],headers:{common:{Accept:"application/json, text/plain, */*"},patch:utils.merge(DEFAULT_CONTENT_TYPE),post:utils.merge(DEFAULT_CONTENT_TYPE),put:utils.merge(DEFAULT_CONTENT_TYPE)},timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"}},{"./utils":17}],7:[function(require,module,exports){"use strict";module.exports=function bind(fn,thisArg){return function wrap(){var args=new Array(arguments.length);for(var i=0;i<args.length;i++){args[i]=arguments[i]}return fn.apply(thisArg,args)}}},{}],8:[function(require,module,exports){"use strict";var chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function InvalidCharacterError(message){this.message=message}InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.code=5;InvalidCharacterError.prototype.name="InvalidCharacterError";function btoa(input){var str=String(input);var output="";for(var block,charCode,idx=0,map=chars;str.charAt(idx|0)||(map="=",idx%1);output+=map.charAt(63&block>>8-idx%1*8)){charCode=str.charCodeAt(idx+=3/4);if(charCode>255){throw new InvalidCharacterError("INVALID_CHARACTER_ERR: DOM Exception 5")}block=block<<8|charCode}return output}module.exports=btoa},{}],9:[function(require,module,exports){"use strict";var utils=require("./../utils");function encode(val){return encodeURIComponent(val).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}module.exports=function buildURL(url,params,paramsSerializer){if(!params){return url}var serializedParams;if(paramsSerializer){serializedParams=paramsSerializer(params)}else{var parts=[];utils.forEach(params,function serialize(val,key){if(val===null||typeof val==="undefined"){return}if(utils.isArray(val)){key=key+"[]"}if(!utils.isArray(val)){val=[val]}utils.forEach(val,function parseValue(v){if(utils.isDate(v)){v=v.toISOString()}else if(utils.isObject(v)){v=JSON.stringify(v)}parts.push(encode(key)+"="+encode(v))})});serializedParams=parts.join("&")}if(serializedParams){url+=(url.indexOf("?")===-1?"?":"&")+serializedParams}return url}},{"./../utils":17}],10:[function(require,module,exports){"use strict";module.exports=function combineURLs(baseURL,relativeURL){return baseURL.replace(/\/+$/,"")+"/"+relativeURL.replace(/^\/+/,"")}},{}],11:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write(name,value,expires,path,domain,secure){var cookie=[];cookie.push(name+"="+encodeURIComponent(value));if(utils.isNumber(expires)){cookie.push("expires="+new Date(expires).toGMTString())}if(utils.isString(path)){cookie.push("path="+path)}if(utils.isString(domain)){cookie.push("domain="+domain)}if(secure===true){cookie.push("secure")}document.cookie=cookie.join("; ")},read:function read(name){var match=document.cookie.match(new RegExp("(^|;\\s*)("+name+")=([^;]*)"));return match?decodeURIComponent(match[3]):null},remove:function remove(name){this.write(name,"",Date.now()-864e5)}}}():function nonStandardBrowserEnv(){return{write:function write(){},read:function read(){return null},remove:function remove(){}}}()},{"./../utils":17}],12:[function(require,module,exports){"use strict";module.exports=function isAbsoluteURL(url){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url)}},{}],13:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){var msie=/(msie|trident)/i.test(navigator.userAgent);var urlParsingNode=document.createElement("a");var originURL;function resolveURL(url){var href=url;if(msie){urlParsingNode.setAttribute("href",href);href=urlParsingNode.href}urlParsingNode.setAttribute("href",href);return{href:urlParsingNode.href,protocol:urlParsingNode.protocol?urlParsingNode.protocol.replace(/:$/,""):"",host:urlParsingNode.host,search:urlParsingNode.search?urlParsingNode.search.replace(/^\?/,""):"",hash:urlParsingNode.hash?urlParsingNode.hash.replace(/^#/,""):"",hostname:urlParsingNode.hostname,port:urlParsingNode.port,pathname:urlParsingNode.pathname.charAt(0)==="/"?urlParsingNode.pathname:"/"+urlParsingNode.pathname}}originURL=resolveURL(window.location.href);return function isURLSameOrigin(requestURL){var parsed=utils.isString(requestURL)?resolveURL(requestURL):requestURL;return parsed.protocol===originURL.protocol&&parsed.host===originURL.host}}():function nonStandardBrowserEnv(){return function isURLSameOrigin(){return true}}()},{"./../utils":17}],14:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=function parseHeaders(headers){var parsed={};var key;var val;var i;if(!headers){return parsed}utils.forEach(headers.split("\n"),function parser(line){i=line.indexOf(":");key=utils.trim(line.substr(0,i)).toLowerCase();val=utils.trim(line.substr(i+1));if(key){parsed[key]=parsed[key]?parsed[key]+", "+val:val}});return parsed}},{"./../utils":17}],15:[function(require,module,exports){"use strict";module.exports=function spread(callback){return function wrap(arr){return callback.apply(null,arr)}}},{}],16:[function(require,module,exports){"use strict";var utils=require("./../utils");module.exports=function transformData(data,headers,fns){utils.forEach(fns,function transform(fn){data=fn(data,headers)});return data}},{"./../utils":17}],17:[function(require,module,exports){"use strict";var toString=Object.prototype.toString;function isArray(val){return toString.call(val)==="[object Array]"}function isArrayBuffer(val){return toString.call(val)==="[object ArrayBuffer]"}function isFormData(val){return toString.call(val)==="[object FormData]"}function isArrayBufferView(val){var result;if(typeof ArrayBuffer!=="undefined"&&ArrayBuffer.isView){result=ArrayBuffer.isView(val)}else{result=val&&val.buffer&&val.buffer instanceof ArrayBuffer}return result}function isString(val){return typeof val==="string"}function isNumber(val){return typeof val==="number"}function isUndefined(val){return typeof val==="undefined"}function isObject(val){return val!==null&&typeof val==="object"}function isDate(val){return toString.call(val)==="[object Date]"}function isFile(val){return toString.call(val)==="[object File]"}function isBlob(val){return toString.call(val)==="[object Blob]"}function trim(str){return str.replace(/^\s*/,"").replace(/\s*$/,"")}function isStandardBrowserEnv(){return typeof window!=="undefined"&&typeof document!=="undefined"&&typeof document.createElement==="function"}function forEach(obj,fn){if(obj===null||typeof obj==="undefined"){return}if(typeof obj!=="object"&&!isArray(obj)){obj=[obj]}if(isArray(obj)){for(var i=0,l=obj.length;i<l;i++){fn.call(null,obj[i],i,obj)}}else{for(var key in obj){if(obj.hasOwnProperty(key)){fn.call(null,obj[key],key,obj)}}}}function merge(){var result={};function assignValue(val,key){result[key]=val}for(var i=0,l=arguments.length;i<l;i++){forEach(arguments[i],assignValue)}return result}module.exports={isArray:isArray,isArrayBuffer:isArrayBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,trim:trim}},{}],18:[function(require,module,exports){"use strict";module.exports=resolveResponse;function resolveResponse(response){walkMutate(response,isLink,function(link){return getLink(response,link)||link});return response.items||[]}function isLink(object){return object&&object.sys&&object.sys.type==="Link"}function getLink(response,link){var type=link.sys.linkType;var id=link.sys.id;var pred=function(resource){return resource.sys.type===type&&resource.sys.id===id};return find(response.items,pred)||response.includes&&find(response.includes[type],pred)}function walkMutate(input,pred,mutator){if(pred(input))return mutator(input);if(input&&typeof input=="object"){for(var key in input){if(input.hasOwnProperty(key)){input[key]=walkMutate(input[key],pred,mutator)}}return input}return input}function find(array,pred){if(!array){return}for(var i=0,len=array.length;i<len;i++){if(pred(array[i])){return array[i]}}}},{}],19:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],20:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&";eq=eq||"=";var obj={};if(typeof qs!=="string"||qs.length===0){return obj}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;if(maxKeys>0&&len>maxKeys){len=maxKeys}for(var i=0;i<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],21:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}}).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],22:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":20,"./encode":21}],contentful:[function(require,module,exports){"use strict";var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var _slicedToArray=function(arr,i){if(Array.isArray(arr)){return arr}else if(Symbol.iterator in Object(arr)){var _arr=[];for(var _iterator=arr[Symbol.iterator](),_step;!(_step=_iterator.next()).done;){_arr.push(_step.value);if(i&&_arr.length===i)break}return _arr}else{throw new TypeError("Invalid attempt to destructure non-iterable instance")}};var _createClass=function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=true;if(prop.value)prop.writable=true}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};exports.createClient=createClient;Object.defineProperty(exports,"__esModule",{value:true});"use strict";var axios=_interopRequire(require("axios"));var resolveResponse=_interopRequire(require("contentful-resolve-response"));var querystring=_interopRequire(require("querystring"));function createClient(options){return new Client(options||{})}var Client=function(){function Client(_ref){var accessToken=_ref.accessToken;var space=_ref.space;var secure=_ref.secure;var host=_ref.host;var headers=_ref.headers;var agent=_ref.agent;_classCallCheck(this,Client);if(!accessToken){throw new TypeError("Expected property accessToken")}if(!space){throw new TypeError("Expected property space")}var insecure=secure===false;var _ref2=host&&host.split(":")||[];var _ref22=_slicedToArray(_ref2,2);var hostname=_ref22[0];var port=_ref22[1];hostname=hostname||"cdn.contentful.com";port=port||(insecure?80:443);this.options={baseUrl:""+(insecure?"http":"https")+"://"+hostname+":"+port+"/spaces/"+space,accessToken:accessToken,headers:headers||{},resolveLinks:true};this.agent=agent}_createClass(Client,{_request:{value:function _request(path,query){if(!query){query={}}query.access_token=this.options.accessToken;var params={headers:this.options.headers,method:"get",url:""+this.options.baseUrl+""+path+"?"+querystring.stringify(query)};if(this.agent)params.agent=this.agent;params.headers["Content-Type"]="application/vnd.contentful.delivery.v1+json";params.headers["X-Contentful-User-Agent"]="contentful.js/2.x";return axios(params).then(function(response){return response.data})["catch"](function(error){throw error.data})}},asset:{value:function asset(id,callback){return nodeify(this._request("/assets/"+id).then(parseResource),callback)}},assets:{value:function assets(object,callback){var query=new Query(object);var deferred=this._request("/assets",query).then(makeSearchResultParser({resolveLinks:this.options.resolveLinks}));return nodeify(deferred,callback)}},contentType:{value:function contentType(id,callback){var deferred=this._request("/content_types/"+id).then(ContentType.parse);return nodeify(deferred,callback)}},contentTypes:{value:function contentTypes(object,callback){var query=new Query(object);var deferred=this._request("/content_types",query).then(makeSearchResultParser({resolveLinks:this.options.resolveLinks}));return nodeify(deferred,callback)}},entry:{value:function entry(id,callback){var deferred=this._request("/entries/"+id).then(Entry.parse);return nodeify(deferred,callback)}},entries:{value:function entries(object,callback){var query=new Query(object);var deferred=this._request("/entries",query).then(makeSearchResultParser({resolveLinks:this.options.resolveLinks}));return nodeify(deferred,callback)}},space:{value:function space(callback){return nodeify(this._request(""),callback)}},_pagedSync:{value:function _pagedSync(sync){var self=this;return this._request("/sync",sync.query).then(function(data){sync.append(data);if(!sync.done){return self._pagedSync(sync)}else{return{items:sync.items,nextSyncToken:sync.nextSyncToken}}})}},sync:{value:function sync(object,callback){if(!object||!object.initial&&!object.nextSyncToken){throw new Error("Please provide either the initial flag or a nextSyncToken for syncing")}if(object.nextSyncToken){object.sync_token=object.nextSyncToken;delete object.initial;delete object.nextSyncToken}var query=new Query(object);var parseSearchResult=makeSearchResultParser({resolveLinks:false});var deferred=this._pagedSync(new Sync(query)).then(function(response){response.items=parseSearchResult(response);return response});return nodeify(deferred,callback)}}});return Client}();var Asset=function(){function Asset(_ref){var sys=_ref.sys;var fields=_ref.fields;_classCallCheck(this,Asset);this.sys=new Sys(sys);this.fields=fields}_createClass(Asset,null,{parse:{value:function parse(object){return new Asset(object)}}});return Asset}();var Entry=function(){function Entry(_ref){var sys=_ref.sys;var fields=_ref.fields;_classCallCheck(this,Entry);this.sys=new Sys(sys);this.fields=fields}_createClass(Entry,null,{parse:{value:function parse(object){return new Entry(object)}}});return Entry}();var ContentType=function(){function ContentType(_ref){var sys=_ref.sys;var fields=_ref.fields;var name=_ref.name;var displayField=_ref.displayField;_classCallCheck(this,ContentType);this.sys=new Sys(sys);this.name=name;this.displayField=displayField;this.fields=fields&&fields.map(Field.parse)}_createClass(ContentType,null,{parse:{value:function parse(object){return new ContentType(object)}}});return ContentType}();var Field=function(){function Field(object){_classCallCheck(this,Field);for(var k in object){this[k]=object[k]}}_createClass(Field,null,{parse:{value:function parse(object){return new Field(object)}}});return Field}();var Query=function(){function Query(object){_classCallCheck(this,Query);for(var k in object){this[k]=object[k]}}_createClass(Query,{toQueryString:{value:function toQueryString(){return querystring.stringify(this)}}},{parse:{value:function parse(object){return new Query(stringifyArrayValues(object))}}});return Query}();var Space=function(){function Space(){var props=arguments[0]===undefined?{}:arguments[0];_classCallCheck(this,Space);for(var k in props){this[k]=props[k]}}_createClass(Space,null,{parse:{value:function parse(object){return new Space(object)}}});return Space}();var Sys=function(){function Sys(_ref){var id=_ref.id;var revision=_ref.revision;var type=_ref.type;var locale=_ref.locale;var contentType=_ref.contentType;var createdAt=_ref.createdAt;var linkType=_ref.linkType;var updatedAt=_ref.updatedAt;var space=_ref.space;_classCallCheck(this,Sys);this.id=id;this.revision=revision;this.type=type;this.locale=locale;this.space=space&&Link.parse(space);this.contentType=contentType&&new Link(contentType);this.createdAt=createdAt&&new Date(createdAt);this.updatedAt=updatedAt&&new Date(updatedAt)}_createClass(Sys,null,{parse:{value:function parse(object){return new Sys(object)}}});return Sys}();var Link=function(){function Link(_ref){var sys=_ref.sys;_classCallCheck(this,Link);this.sys=new Sys(sys)}_createClass(Link,null,{parse:{value:function parse(object){return new Link(object)}}});return Link}();var Sync=function(){function Sync(query){_classCallCheck(this,Sync);this.query=query;this.items=[];this.done=false}_createClass(Sync,{append:{value:function append(data){var _this=this;this.items=this.items.concat(data.items);if(data.nextPageUrl){var nextPageUrl=data.nextPageUrl.split("?");this.query=Object.keys(this.query).reduce(function(query,key){if(key!=="initial"&&key!=="type"&&key!=="sync_token"){query[key]=_this.query[key]}return query},{});this.query.sync_token=querystring.parse(nextPageUrl[1]).sync_token}else if(data.nextSyncUrl){var nextSyncUrl=data.nextSyncUrl.split("?");this.nextSyncToken=querystring.parse(nextSyncUrl[1]).sync_token;this.done=true}}}});return Sync}();var parseableResourceTypes={Asset:Asset,ContentType:ContentType,Entry:Entry,Space:Space};function isParseableResource(object){return object&&object.sys&&object.sys.type in parseableResourceTypes}function parseResource(resource){var Type=parseableResourceTypes[resource.sys.type];return Type.parse(resource)}function makeSearchResultParser(options){return function parseSearchResult(object){walkMutate(object,isParseableResource,parseResource);var items=options.resolveLinks?resolveResponse(object):object.items;Object.defineProperties(items,{limit:{value:object.limit,enumerable:false},skip:{value:object.skip,enumerable:false},total:{value:object.total,enumerable:false}});return items}}function stringifyArrayValues(object){return keys(object).reduce(function(result,key){var value=object[key];result[key]=Array.isArray(value)?value.join(","):value;return result},{})}function walkMutate(input,pred,mutator){if(pred(input)){return mutator(input)}if(input&&typeof input==="object"){for(var key in input){input[key]=walkMutate(input[key],pred,mutator)}}return input}function nodeify(deferred,callback){if(callback){return deferred.then(function(response){callback(null,response);return response})["catch"](function(error){callback(error);throw error})}return deferred}},{axios:1,"contentful-resolve-response":18,querystring:22}]},{},[]);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){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],2:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],3:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],util:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){ | |
str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":3,_process:2,inherits:1}]},{},[]);var contentful=require("contentful");var util=require("util");var client=contentful.createClient({space:"developer_bookshelf",accessToken:"0b7f6x59a0"});client.entry("5PeGS2SoZGSa4GuiQsigQu").then(function(entry){document.getElementById("req1").innerHTML=util.inspect(entry,{depth:null})});client.contentType("book").then(function(contentType){document.getElementById("req2").innerHTML=util.inspect(contentType,{depth:null})}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "requirebin-sketch", | |
"version": "1.0.0", | |
"dependencies": { | |
"contentful": "2.1.2" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- contents of this file will be placed inside the <body> --> | |
<pre><code id="req1"></code></pre> | |
<pre><code id="req2"></code></pre> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- contents of this file will be placed inside the <head> --> | |
<style> | |
body { | |
background: #000; | |
} | |
/* Code Styles */ | |
pre { | |
white-space: pre-wrap; | |
white-space: -moz-pre-wrap; | |
white-space: -o-pre-wrap; | |
word-wrap: break-word; | |
} | |
code { | |
font-family: Courier, 'New Courier', monospace; | |
font-size: 13px; | |
border-radius: 5px; | |
-moz-border-radius: 5px; | |
-webkit-border-radius: 5px; | |
margin: 1em 0; | |
background-color: #000000; | |
color: green; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment