made with requirebin
Last active
August 29, 2015 14:17
-
-
Save vvo/b97742c9c3c91f31b505 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
| // hello world | |
| var algoliasearch = require('algoliasearch'); | |
| var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76', {protocol: 'http:'}); | |
| var query = 'ab'; | |
| client.startQueriesBatch(); | |
| client.addQueryInBatch( | |
| 'contacts', // index name | |
| query, { | |
| hitsPerPage: 3 | |
| } | |
| ); | |
| client.addQueryInBatch('contacts', query, {hitsPerPage: 5}); | |
| client.sendQueriesBatch(searchMultiCallback); | |
| function searchMultiCallback(err, content) { | |
| if (err) { | |
| console.error(err); | |
| return; | |
| } | |
| var log = document.body.appendChild(document.createElement('div')); | |
| log.innerHTML = ''; | |
| var contacts = content.results[0]; | |
| for (var i = 0; i < contacts.hits.length; ++i) { | |
| log.innerHTML += JSON.stringify(contacts.hits[i]); | |
| } | |
| var products = contacts.results[1]; | |
| for (var i = 0; i < contacts.hits.length; ++i) { | |
| log.innerHTML += JSON.stringify(contacts.hits[i]); | |
| } | |
| } |
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){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")}},{}],2:[function(require,module,exports){(function(process,global){(function(){"use strict";function $$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function $$utils$$isFunction(x){return typeof x==="function"}function $$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var $$utils$$_isArray;if(!Array.isArray){$$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{$$utils$$_isArray=Array.isArray}var $$utils$$isArray=$$utils$$_isArray;var $$utils$$now=Date.now||function(){return(new Date).getTime()};function $$utils$$F(){}var $$utils$$o_create=Object.create||function(o){if(arguments.length>1){throw new Error("Second argument not supported")}if(typeof o!=="object"){throw new TypeError("Argument must be an object")}$$utils$$F.prototype=o;return new $$utils$$F};var $$asap$$len=0;var $$asap$$default=function asap(callback,arg){$$asap$$queue[$$asap$$len]=callback;$$asap$$queue[$$asap$$len+1]=arg;$$asap$$len+=2;if($$asap$$len===2){$$asap$$scheduleFlush()}};var $$asap$$browserGlobal=typeof window!=="undefined"?window:{};var $$asap$$BrowserMutationObserver=$$asap$$browserGlobal.MutationObserver||$$asap$$browserGlobal.WebKitMutationObserver;var $$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function $$asap$$useNextTick(){return function(){process.nextTick($$asap$$flush)}}function $$asap$$useMutationObserver(){var iterations=0;var observer=new $$asap$$BrowserMutationObserver($$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function $$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=$$asap$$flush;return function(){channel.port2.postMessage(0)}}function $$asap$$useSetTimeout(){return function(){setTimeout($$asap$$flush,1)}}var $$asap$$queue=new Array(1e3);function $$asap$$flush(){for(var i=0;i<$$asap$$len;i+=2){var callback=$$asap$$queue[i];var arg=$$asap$$queue[i+1];callback(arg);$$asap$$queue[i]=undefined;$$asap$$queue[i+1]=undefined}$$asap$$len=0}var $$asap$$scheduleFlush;if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){$$asap$$scheduleFlush=$$asap$$useNextTick()}else if($$asap$$BrowserMutationObserver){$$asap$$scheduleFlush=$$asap$$useMutationObserver()}else if($$asap$$isWorker){$$asap$$scheduleFlush=$$asap$$useMessageChannel()}else{$$asap$$scheduleFlush=$$asap$$useSetTimeout()}function $$$internal$$noop(){}var $$$internal$$PENDING=void 0;var $$$internal$$FULFILLED=1;var $$$internal$$REJECTED=2;var $$$internal$$GET_THEN_ERROR=new $$$internal$$ErrorObject;function $$$internal$$selfFullfillment(){return new TypeError("You cannot resolve a promise with itself")}function $$$internal$$cannotReturnOwn(){return new TypeError("A promises callback cannot return that same promise.")}function $$$internal$$getThen(promise){try{return promise.then}catch(error){$$$internal$$GET_THEN_ERROR.error=error;return $$$internal$$GET_THEN_ERROR}}function $$$internal$$tryThen(then,value,fulfillmentHandler,rejectionHandler){try{then.call(value,fulfillmentHandler,rejectionHandler)}catch(e){return e}}function $$$internal$$handleForeignThenable(promise,thenable,then){$$asap$$default(function(promise){var sealed=false;var error=$$$internal$$tryThen(then,thenable,function(value){if(sealed){return}sealed=true;if(thenable!==value){$$$internal$$resolve(promise,value)}else{$$$internal$$fulfill(promise,value)}},function(reason){if(sealed){return}sealed=true;$$$internal$$reject(promise,reason)},"Settle: "+(promise._label||" unknown promise"));if(!sealed&&error){sealed=true;$$$internal$$reject(promise,error)}},promise)}function $$$internal$$handleOwnThenable(promise,thenable){if(thenable._state===$$$internal$$FULFILLED){$$$internal$$fulfill(promise,thenable._result)}else if(promise._state===$$$internal$$REJECTED){$$$internal$$reject(promise,thenable._result)}else{$$$internal$$subscribe(thenable,undefined,function(value){$$$internal$$resolve(promise,value)},function(reason){$$$internal$$reject(promise,reason)})}}function $$$internal$$handleMaybeThenable(promise,maybeThenable){if(maybeThenable.constructor===promise.constructor){$$$internal$$handleOwnThenable(promise,maybeThenable)}else{var then=$$$internal$$getThen(maybeThenable);if(then===$$$internal$$GET_THEN_ERROR){$$$internal$$reject(promise,$$$internal$$GET_THEN_ERROR.error)}else if(then===undefined){$$$internal$$fulfill(promise,maybeThenable)}else if($$utils$$isFunction(then)){$$$internal$$handleForeignThenable(promise,maybeThenable,then)}else{$$$internal$$fulfill(promise,maybeThenable)}}}function $$$internal$$resolve(promise,value){if(promise===value){$$$internal$$reject(promise,$$$internal$$selfFullfillment())}else if($$utils$$objectOrFunction(value)){$$$internal$$handleMaybeThenable(promise,value)}else{$$$internal$$fulfill(promise,value)}}function $$$internal$$publishRejection(promise){if(promise._onerror){promise._onerror(promise._result)}$$$internal$$publish(promise)}function $$$internal$$fulfill(promise,value){if(promise._state!==$$$internal$$PENDING){return}promise._result=value;promise._state=$$$internal$$FULFILLED;if(promise._subscribers.length===0){}else{$$asap$$default($$$internal$$publish,promise)}}function $$$internal$$reject(promise,reason){if(promise._state!==$$$internal$$PENDING){return}promise._state=$$$internal$$REJECTED;promise._result=reason;$$asap$$default($$$internal$$publishRejection,promise)}function $$$internal$$subscribe(parent,child,onFulfillment,onRejection){var subscribers=parent._subscribers;var length=subscribers.length;parent._onerror=null;subscribers[length]=child;subscribers[length+$$$internal$$FULFILLED]=onFulfillment;subscribers[length+$$$internal$$REJECTED]=onRejection;if(length===0&&parent._state){$$asap$$default($$$internal$$publish,parent)}}function $$$internal$$publish(promise){var subscribers=promise._subscribers;var settled=promise._state;if(subscribers.length===0){return}var child,callback,detail=promise._result;for(var i=0;i<subscribers.length;i+=3){child=subscribers[i];callback=subscribers[i+settled];if(child){$$$internal$$invokeCallback(settled,child,callback,detail)}else{callback(detail)}}promise._subscribers.length=0}function $$$internal$$ErrorObject(){this.error=null}var $$$internal$$TRY_CATCH_ERROR=new $$$internal$$ErrorObject;function $$$internal$$tryCatch(callback,detail){try{return callback(detail)}catch(e){$$$internal$$TRY_CATCH_ERROR.error=e;return $$$internal$$TRY_CATCH_ERROR}}function $$$internal$$invokeCallback(settled,promise,callback,detail){var hasCallback=$$utils$$isFunction(callback),value,error,succeeded,failed;if(hasCallback){value=$$$internal$$tryCatch(callback,detail);if(value===$$$internal$$TRY_CATCH_ERROR){failed=true;error=value.error;value=null}else{succeeded=true}if(promise===value){$$$internal$$reject(promise,$$$internal$$cannotReturnOwn());return}}else{value=detail;succeeded=true}if(promise._state!==$$$internal$$PENDING){}else if(hasCallback&&succeeded){$$$internal$$resolve(promise,value)}else if(failed){$$$internal$$reject(promise,error)}else if(settled===$$$internal$$FULFILLED){$$$internal$$fulfill(promise,value)}else if(settled===$$$internal$$REJECTED){$$$internal$$reject(promise,value)}}function $$$internal$$initializePromise(promise,resolver){try{resolver(function resolvePromise(value){$$$internal$$resolve(promise,value)},function rejectPromise(reason){$$$internal$$reject(promise,reason)})}catch(e){$$$internal$$reject(promise,e)}}function $$$enumerator$$makeSettledResult(state,position,value){if(state===$$$internal$$FULFILLED){return{state:"fulfilled",value:value}}else{return{state:"rejected",reason:value}}}function $$$enumerator$$Enumerator(Constructor,input,abortOnReject,label){this._instanceConstructor=Constructor;this.promise=new Constructor($$$internal$$noop,label);this._abortOnReject=abortOnReject;if(this._validateInput(input)){this._input=input;this.length=input.length;this._remaining=input.length;this._init();if(this.length===0){$$$internal$$fulfill(this.promise,this._result)}else{this.length=this.length||0;this._enumerate();if(this._remaining===0){$$$internal$$fulfill(this.promise,this._result)}}}else{$$$internal$$reject(this.promise,this._validationError())}}$$$enumerator$$Enumerator.prototype._validateInput=function(input){return $$utils$$isArray(input)};$$$enumerator$$Enumerator.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")};$$$enumerator$$Enumerator.prototype._init=function(){this._result=new Array(this.length)};var $$$enumerator$$default=$$$enumerator$$Enumerator;$$$enumerator$$Enumerator.prototype._enumerate=function(){var length=this.length;var promise=this.promise;var input=this._input;for(var i=0;promise._state===$$$internal$$PENDING&&i<length;i++){this._eachEntry(input[i],i)}};$$$enumerator$$Enumerator.prototype._eachEntry=function(entry,i){var c=this._instanceConstructor;if($$utils$$isMaybeThenable(entry)){if(entry.constructor===c&&entry._state!==$$$internal$$PENDING){entry._onerror=null;this._settledAt(entry._state,i,entry._result)}else{this._willSettleAt(c.resolve(entry),i)}}else{this._remaining--;this._result[i]=this._makeResult($$$internal$$FULFILLED,i,entry)}};$$$enumerator$$Enumerator.prototype._settledAt=function(state,i,value){var promise=this.promise;if(promise._state===$$$internal$$PENDING){this._remaining--;if(this._abortOnReject&&state===$$$internal$$REJECTED){$$$internal$$reject(promise,value)}else{this._result[i]=this._makeResult(state,i,value)}}if(this._remaining===0){$$$internal$$fulfill(promise,this._result)}};$$$enumerator$$Enumerator.prototype._makeResult=function(state,i,value){return value};$$$enumerator$$Enumerator.prototype._willSettleAt=function(promise,i){var enumerator=this;$$$internal$$subscribe(promise,undefined,function(value){enumerator._settledAt($$$internal$$FULFILLED,i,value)},function(reason){enumerator._settledAt($$$internal$$REJECTED,i,reason)})};var $$promise$all$$default=function all(entries,label){return new $$$enumerator$$default(this,entries,true,label).promise};var $$promise$race$$default=function race(entries,label){var Constructor=this;var promise=new Constructor($$$internal$$noop,label);if(!$$utils$$isArray(entries)){$$$internal$$reject(promise,new TypeError("You must pass an array to race."));return promise}var length=entries.length;function onFulfillment(value){$$$internal$$resolve(promise,value)}function onRejection(reason){$$$internal$$reject(promise,reason)}for(var i=0;promise._state===$$$internal$$PENDING&&i<length;i++){$$$internal$$subscribe(Constructor.resolve(entries[i]),undefined,onFulfillment,onRejection)}return promise};var $$promise$resolve$$default=function resolve(object,label){var Constructor=this;if(object&&typeof object==="object"&&object.constructor===Constructor){return object}var promise=new Constructor($$$internal$$noop,label);$$$internal$$resolve(promise,object);return promise};var $$promise$reject$$default=function reject(reason,label){var Constructor=this;var promise=new Constructor($$$internal$$noop,label);$$$internal$$reject(promise,reason);return promise};var $$es6$promise$promise$$counter=0;function $$es6$promise$promise$$needsResolver(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function $$es6$promise$promise$$needsNew(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var $$es6$promise$promise$$default=$$es6$promise$promise$$Promise;function $$es6$promise$promise$$Promise(resolver){this._id=$$es6$promise$promise$$counter++;this._state=undefined;this._result=undefined;this._subscribers=[];if($$$internal$$noop!==resolver){if(!$$utils$$isFunction(resolver)){$$es6$promise$promise$$needsResolver()}if(!(this instanceof $$es6$promise$promise$$Promise)){$$es6$promise$promise$$needsNew()}$$$internal$$initializePromise(this,resolver)}}$$es6$promise$promise$$Promise.all=$$promise$all$$default;$$es6$promise$promise$$Promise.race=$$promise$race$$default;$$es6$promise$promise$$Promise.resolve=$$promise$resolve$$default;$$es6$promise$promise$$Promise.reject=$$promise$reject$$default;$$es6$promise$promise$$Promise.prototype={constructor:$$es6$promise$promise$$Promise,then:function(onFulfillment,onRejection){var parent=this;var state=parent._state;if(state===$$$internal$$FULFILLED&&!onFulfillment||state===$$$internal$$REJECTED&&!onRejection){return this}var child=new this.constructor($$$internal$$noop);var result=parent._result;if(state){var callback=arguments[state-1];$$asap$$default(function(){$$$internal$$invokeCallback(state,child,callback,result)})}else{$$$internal$$subscribe(parent,child,onFulfillment,onRejection)}return child},"catch":function(onRejection){return this.then(null,onRejection)}};var $$es6$promise$polyfill$$default=function polyfill(){var local;if(typeof global!=="undefined"){local=global}else if(typeof window!=="undefined"&&window.document){local=window}else{local=self}var es6PromiseSupport="Promise"in local&&"resolve"in local.Promise&&"reject"in local.Promise&&"all"in local.Promise&&"race"in local.Promise&&function(){var resolve;new local.Promise(function(r){resolve=r});return $$utils$$isFunction(resolve)}();if(!es6PromiseSupport){local.Promise=$$es6$promise$promise$$default}};var es6$promise$umd$$ES6Promise={Promise:$$es6$promise$promise$$default,polyfill:$$es6$promise$polyfill$$default};if(typeof define==="function"&&define["amd"]){define(function(){return es6$promise$umd$$ES6Promise})}else if(typeof module!=="undefined"&&module["exports"]){module["exports"]=es6$promise$umd$$ES6Promise}else if(typeof this!=="undefined"){this["ES6Promise"]=es6$promise$umd$$ES6Promise}}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:1}],3:[function(require,module,exports){(function(process){module.exports=AlgoliaSearch;function AlgoliaSearch(applicationID,apiKey,opts,_request){var usage="Usage: algoliasearch(applicationID, apiKey, opts)";if(!applicationID){throw new Error("Please provide an application ID. "+usage)}if(!apiKey){throw new Error("Please provide an API key. "+usage)}opts=opts||{};if(opts.timeout===undefined){opts.timeout=2e3}if(opts.protocol===undefined){opts.protocol=document&&document.location.protocol||"http:"}if(opts.hosts===undefined){opts.hosts=[]}if(opts.tld===undefined){opts.tld="net"}if(!/:$/.test(opts.protocol)){opts.protocol=opts.protocol+":"}if(opts.hosts.length===0){opts.hosts=shuffle([applicationID+"-1.algolia."+opts.tld,applicationID+"-2.algolia."+opts.tld,applicationID+"-3.algolia."+opts.tld]);opts.hosts.unshift(applicationID+"-dsn.algolia."+opts.tld)}opts.hosts=map(opts.hosts,function prependProtocol(host){return opts.protocol+"//"+host});this.applicationID=applicationID;this.apiKey=apiKey;this.hosts=opts.hosts;this.currentHostIndex=0;this.requestTimeout=opts.timeout;this.extraHeaders=[];this.cache={};this._request=_request}AlgoliaSearch.prototype={deleteIndex:function(indexName,callback){return this._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(indexName),callback:callback})},moveIndex:function(srcIndexName,dstIndexName,callback){var postObj={operation:"move",destination:dstIndexName};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(srcIndexName)+"/operation",body:postObj,callback:callback})},copyIndex:function(srcIndexName,dstIndexName,callback){var postObj={operation:"copy",destination:dstIndexName};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(srcIndexName)+"/operation",body:postObj,callback:callback})},getLogs:function(offset,length,callback){if(arguments.length===0||typeof offset==="function"){callback=offset;offset=0;length=10}else if(arguments.length===1||typeof length==="function"){callback=length;length=10}return this._jsonRequest({method:"GET",url:"/1/logs?offset="+offset+"&length="+length,callback:callback})},listIndexes:function(page,callback){var params="";if(page===undefined||typeof page==="function"){callback=page}else{params="?page="+page}return this._jsonRequest({method:"GET",url:"/1/indexes"+params,callback:callback})},initIndex:function(indexName){return new this.Index(this,indexName)},listUserKeys:function(callback){return this._jsonRequest({method:"GET",url:"/1/keys",callback:callback})},getUserKeyACL:function(key,callback){return this._jsonRequest({method:"GET",url:"/1/keys/"+key,callback:callback})},deleteUserKey:function(key,callback){return this._jsonRequest({method:"DELETE",url:"/1/keys/"+key,callback:callback})},addUserKey:function(acls,callback){return this.addUserKeyWithValidity(acls,{validity:0,maxQueriesPerIPPerHour:0,maxHitsPerQuery:0},callback)},addUserKeyWithValidity:function(acls,params,callback){var aclsObject={};aclsObject.acl=acls;aclsObject.validity=params.validity;aclsObject.maxQueriesPerIPPerHour=params.maxQueriesPerIPPerHour;aclsObject.maxHitsPerQuery=params.maxHitsPerQuery;return this._jsonRequest({method:"POST",url:"/1/keys",body:aclsObject,callback:callback})},setSecurityTags:function(tags){if(Object.prototype.toString.call(tags)==="[object Array]"){var strTags=[];for(var i=0;i<tags.length;++i){if(Object.prototype.toString.call(tags[i])==="[object Array]"){var oredTags=[];for(var j=0;j<tags[i].length;++j){oredTags.push(tags[i][j])}strTags.push("("+oredTags.join(",")+")")}else{strTags.push(tags[i])}}tags=strTags.join(",")}this.tagFilters=tags},setUserToken:function(userToken){this.userToken=userToken},startQueriesBatch:function(){this.batch=[]},addQueryInBatch:function(indexName,query,args){var params="query="+encodeURIComponent(query);if(!this._isUndefined(args)&&args!==null){params=this._getSearchParams(args,params)}this.batch.push({indexName:indexName,params:params})},clearCache:function(){this.cache={}},sendQueriesBatch:function(callback){var as=this;var params={requests:[]};for(var i=0;i<as.batch.length;++i){params.requests.push(as.batch[i])}return this._sendQueriesBatch(params,callback)},setRequestTimeout:function(milliseconds){if(milliseconds){this.requestTimeout=parseInt(milliseconds,10)}},Index:function(algoliasearch,indexName){this.indexName=indexName;this.as=algoliasearch;this.typeAheadArgs=null;this.typeAheadValueOption=null;this.cache={}},setExtraHeader:function(key,value){this.extraHeaders.push({key:key,value:value})},_sendQueriesBatch:function(params,callback){return this._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/*/queries",body:params,fallback:{method:"GET",url:"/1/indexes/*",body:{params:function(){var reqParams="";for(var i=0;i<params.requests.length;++i){var q="/1/indexes/"+encodeURIComponent(params.requests[i].indexName)+"?"+params.requests[i].params;reqParams+=i+"="+encodeURIComponent(q)+"&"}return reqParams}()}},callback:callback})},_jsonRequest:function(opts){var cache=opts.cache;var cacheID=opts.url;var client=this;var tries=0;if(opts.body!==undefined){cacheID+="_body_"+JSON.stringify(opts.body)}function doRequest(requester,reqOpts){if(cache&&cache[cacheID]!==undefined){return client._request.resolve(cache[cacheID])}if(tries>=client.hosts.length){if(!opts.fallback||requester===client._request.fallback){return client._request.reject(new Error("Cannot connect to the AlgoliaSearch API."+" Send an email to support@algolia.com to report and resolve the issue."))}tries=0;reqOpts.method=opts.fallback.method;reqOpts.url=opts.fallback.url;reqOpts.body=opts.fallback.body;reqOpts.timeout=client.requestTimeout*(tries+1);client.currentHostIndex=0;client.forceFallback=true;return doRequest(client._request.fallback,reqOpts)}var url=reqOpts.url;url+=(url.indexOf("?")===-1?"?":"&")+"X-Algolia-API-Key="+client.apiKey;url+="&X-Algolia-Application-Id="+client.applicationID;if(client.userToken){url+="&X-Algolia-UserToken="+encodeURIComponent(client.userToken)}if(client.tagFilters){url+="&X-Algolia-TagFilters="+encodeURIComponent(client.tagFilters)}for(var i=0;i<client.extraHeaders.length;++i){url+="&"+client.extraHeaders[i].key+"="+client.extraHeaders[i].value}return requester(client.hosts[client.currentHostIndex]+url,{body:reqOpts.body,method:reqOpts.method,timeout:reqOpts.timeout}).then(function success(httpResponse){if(httpResponse instanceof Error){return retryRequest()}var status=httpResponse&&httpResponse.body&&httpResponse.body.message&&httpResponse.body.status||httpResponse.statusCode||httpResponse&&httpResponse.body&&200;var ok=status===200||status===201;var retry=!ok&&Math.floor(status/100)!==4&&Math.floor(status/100)!==1;if(ok&&cache){cache[cacheID]=httpResponse.body}if(ok){return httpResponse.body}if(retry){return retryRequest()}var unrecoverableError=new Error(httpResponse.body&&httpResponse.body.message||"Unknown error");return client._request.reject(unrecoverableError)},tryFallback);function retryRequest(){client.currentHostIndex=++client.currentHostIndex%client.hosts.length;tries+=1;reqOpts.timeout=client.requestTimeout*(tries+1);return doRequest(requester,reqOpts)}function tryFallback(){if(!client.forceFallback){tries=client.hosts.length}else{client.currentHostIndex=++client.currentHostIndex%client.hosts.length;tries+=1}return doRequest(requester,reqOpts)}}var useFallback=client.forceFallback&&opts.fallback;var requestOptions=useFallback?opts.fallback:opts;var promise=doRequest(useFallback?client._request.fallback:client._request,{url:requestOptions.url,method:requestOptions.method,body:requestOptions.body,timeout:client.requestTimeout*(tries+1)});if(opts.callback){promise.then(function okCb(content){process.nextTick(function(){opts.callback(null,content)})},function nookCb(err){process.nextTick(function(){opts.callback(err)})})}else{return promise}},_getSearchParams:function(args,params){if(this._isUndefined(args)||args===null){return params}for(var key in args){if(key!==null&&args.hasOwnProperty(key)){params+=params===""?"":"&";params+=key+"="+encodeURIComponent(Object.prototype.toString.call(args[key])==="[object Array]"?JSON.stringify(args[key]):args[key])}}return params},_isUndefined:function(obj){return obj===void 0}};AlgoliaSearch.prototype.Index.prototype={clearCache:function(){this.cache={}},addObject:function(content,objectID,callback){var indexObj=this;if(arguments.length===1||typeof objectID==="function"){callback=objectID;objectID=undefined}return this.as._jsonRequest({method:objectID!==undefined?"PUT":"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+(objectID!==undefined?"/"+encodeURIComponent(objectID):""),body:content,callback:callback})},addObjects:function(objects,callback){var indexObj=this;var postObj={requests:[]};for(var i=0;i<objects.length;++i){var request={action:"addObject",body:objects[i]};postObj.requests.push(request)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/batch",body:postObj,callback:callback})},getObject:function(objectID,attrs,callback){var indexObj=this;if(arguments.length===1||typeof attrs==="function"){callback=attrs;attrs=undefined}var params="";if(attrs!==undefined){params="?attributes=";for(var i=0;i<attrs.length;++i){if(i!==0){params+=","}params+=attrs[i]}}return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/"+encodeURIComponent(objectID)+params,callback:callback})},partialUpdateObject:function(partialObject,callback){var indexObj=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/"+encodeURIComponent(partialObject.objectID)+"/partial",body:partialObject,callback:callback})},partialUpdateObjects:function(objects,callback){var indexObj=this;var postObj={requests:[]};for(var i=0;i<objects.length;++i){var request={action:"partialUpdateObject",objectID:objects[i].objectID,body:objects[i]};postObj.requests.push(request)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/batch",body:postObj,callback:callback})},saveObject:function(object,callback){var indexObj=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/"+encodeURIComponent(object.objectID),body:object,callback:callback})},saveObjects:function(objects,callback){var indexObj=this;var postObj={requests:[]};for(var i=0;i<objects.length;++i){var request={action:"updateObject",objectID:objects[i].objectID,body:objects[i]};postObj.requests.push(request)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/batch",body:postObj,callback:callback})},deleteObject:function(objectID,callback){if(typeof objectID==="function"||typeof objectID!=="string"&&typeof objectID!=="number"){var err=new Error("Cannot delete an object without an objectID");callback=objectID;if(typeof callback==="function"){return callback(err)}return this.as._request.reject(err)}var indexObj=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/"+encodeURIComponent(objectID),callback:callback})},search:function(query,args,callback){if(arguments.length===0||typeof query==="function"){callback=query;query=""}else if(arguments.length===1||typeof args==="function"){callback=args;args=undefined}if(typeof query==="object"&&query!==null){args=query;query=undefined}else if(query===undefined||query===null){query=""}var params="";if(query!==undefined){params+="query="+encodeURIComponent(query)}if(args!==undefined){params=this.as._getSearchParams(args,params)}return this._search(params,callback)},browse:function(page,hitsPerPage,callback){var indexObj=this;if(arguments.length===1||typeof hitsPerPage==="function"){callback=hitsPerPage;hitsPerPage=undefined}var params="?page="+page;if(!this.as._isUndefined(hitsPerPage)){params+="&hitsPerPage="+hitsPerPage}return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/browse"+params,callback:callback})},ttAdapter:function(params){var self=this;return function(query,cb){self.search(query,params,function(err,content){if(err){cb(err);return}cb(content.hits)})}},waitTask:function(taskID,callback){var indexObj=this;var promise=this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/task/"+taskID}).then(function success(content){if(content.status!=="published"){return new indexObj.as._request.delay(100).then(function(){return indexObj.waitTask(taskID,callback)})}if(callback){process.nextTick(function(){callback(null,content)})}else{return content}},function failure(err){if(callback){process.nextTick(function(){callback(err)})}else{return err}});if(!callback){return promise}},clearIndex:function(callback){var indexObj=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/clear",callback:callback})},getSettings:function(callback){var indexObj=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/settings",callback:callback})},setSettings:function(settings,callback){var indexObj=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/settings",body:settings,callback:callback})},listUserKeys:function(callback){var indexObj=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/keys",callback:callback})},getUserKeyACL:function(key,callback){var indexObj=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/keys/"+key,callback:callback})},deleteUserKey:function(key,callback){var indexObj=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/keys/"+key,callback:callback})},addUserKey:function(acls,callback){var indexObj=this;var aclsObject={};aclsObject.acl=acls;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/keys",body:aclsObject,callback:callback})},addUserKeyWithValidity:function(acls,params,callback){var indexObj=this;var aclsObject={};aclsObject.acl=acls;aclsObject.validity=params.validity;aclsObject.maxQueriesPerIPPerHour=params.maxQueriesPerIPPerHour;aclsObject.maxHitsPerQuery=params.maxHitsPerQuery;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(indexObj.indexName)+"/keys",body:aclsObject,callback:callback})},_search:function(params,callback){return this.as._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/query",body:{params:params},fallback:{method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName),body:{params:params}},callback:callback})},as:null,indexName:null,typeAheadArgs:null,typeAheadValueOption:null};function map(arr,fn){var ret=[];for(var i=0;i<arr.length;++i){ret.push(fn(arr[i],i))}return ret}function shuffle(array){var currentIndex=array.length,temporaryValue,randomIndex;while(0!==currentIndex){randomIndex=Math.floor(Math.random()*currentIndex);currentIndex-=1;temporaryValue=array[currentIndex];array[currentIndex]=array[randomIndex];array[randomIndex]=temporaryValue}return array}}).call(this,require("_process"))},{_process:1}],4:[function(require,module,exports){module.exports=createAlgoliasearch;function createAlgoliasearch(request){function algoliasearch(applicationID,apiKey,opts){var AlgoliaSearch=require("./algoliasearch");return new AlgoliaSearch(applicationID,apiKey,opts,request)}algoliasearch.version="3.0.1";return algoliasearch}},{"./algoliasearch":3}],5:[function(require,module,exports){module.exports=JSONPRequest;var JSONPCounter=0;function JSONPRequest(url,opts,cb){if(opts.method!=="GET"){cb(new Error("Method "+opts.method+" "+url+" is not supported by JSONP."));return}var cbCalled=false;var timedOut=false; | |
| JSONPCounter+=1;var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");var cbName="algoliaJSONP_"+JSONPCounter;var done=false;window[cbName]=function(data){try{delete window[cbName]}catch(e){window[cbName]=undefined}if(timedOut){return}cbCalled=true;clean();cb(null,{body:data})};url+="&callback="+cbName;if(opts.body&&opts.body.params){url+="&"+opts.body.params}var ontimeout=setTimeout(timeout,opts.timeout);script.onreadystatechange=readystatechange;script.onload=success;script.onerror=error;script.async=true;script.defer=true;script.src=url;head.appendChild(script);function success(){if(done||timedOut){return}done=true;if(!cbCalled){clean();cb(new Error("Failed to load JSONP script"))}}function readystatechange(){if(this.readyState==="loaded"||this.readyState==="complete"){success()}}function clean(){clearTimeout(ontimeout);script.onload=null;script.onreadystatechange=null;script.onerror=null;head.removeChild(script);try{delete window[cbName];delete window[cbName+"_loaded"]}catch(e){window[cbName]=null;window[cbName+"_loaded"]=null}}function timeout(){timedOut=true;clean();cb(new Error("Timeout - Could not connect to endpoint "+url))}function error(){if(done||timedOut){return}clean();cb(new Error("Failed to load JSONP script"))}}},{}],6:[function(require,module,exports){module.exports=migrationLayer;function migrationLayer(buildName){var isUsingLatest=require("./is-using-latest");var loadV2=require("./load-v2");var oldGlobals=require("./old-globals");if(isUsingLatest(buildName)){loadV2(buildName)}else{oldGlobals()}}},{"./is-using-latest":7,"./load-v2":8,"./old-globals":9}],7:[function(require,module,exports){module.exports=isUsingLatest;function isUsingLatest(buildName){var toFind=new RegExp("cdn\\.jsdelivr\\.net/algoliasearch/latest/"+buildName.replace(".","\\.")+"(?:\\.min)?\\.js$");var scripts=document.getElementsByTagName("script");var found=false;for(var currentScript=0,nbScripts=scripts.length;currentScript<nbScripts;currentScript++){if(scripts[currentScript].src&&toFind.test(scripts[currentScript].src)){found=true;break}}return found}},{}],8:[function(require,module,exports){(function(global){module.exports=loadV2;function loadV2(buildName){var message="Warning, you are using the `latest` version tag from jsDelivr for the AlgoliaSearch library.\n"+"We updated the AlgoliaSearch JavaScript client to V3, using `latest` is no more recommended.\n"+"Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x";if(global.console){if(global.console.warn){global.console.warn(message)}else if(global.console.log){global.console.log(message)}}document.write('<script src="//cdn.jsdelivr.net/algoliasearch/2.9/'+buildName+'.min.js"></script>')}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],9:[function(require,module,exports){(function(global){module.exports=oldGlobals;function oldGlobals(){var message="You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation."+"\nPlease read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x";global.AlgoliaSearch=function(){throw new Error(message)};global.AlgoliaSearchHelper=function(){throw new Error(message)};AlgoliaExplainResults=function(){throw new Error(message)}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],algoliasearch:[function(require,module,exports){(function(global){var createAlgoliasearch=require("./create-algoliasearch");module.exports=createAlgoliasearch(request);var Promise=global.Promise||require("es6-promise").Promise;var JSONPRequest=require("./jsonp-request");var support={hasXMLHttpRequest:"XMLHttpRequest"in window,hasXDomainRequest:"XDomainRequest"in window,cors:"withCredentials"in new XMLHttpRequest,timeout:"timeout"in new XMLHttpRequest};function request(url,opts){return new Promise(function(resolve,reject){if(!support.cors&&!support.hasXDomainRequest){reject(new Error("CORS not supported"));return}var body=null;var req=support.cors?new XMLHttpRequest:new XDomainRequest;var ontimeout;var timedOut;if(opts.body!==undefined){body=JSON.stringify(opts.body)}if(req instanceof XMLHttpRequest){req.open(opts.method,url,true)}else{req.open(opts.method,url)}if(support.cors&&body&&opts.method!=="GET"){req.setRequestHeader("Content-type","application/x-www-form-urlencoded")}req.onload=load;req.onerror=error;if(support.timeout){req.timeout=opts.timeout;req.ontimeout=timeout}else{ontimeout=setTimeout(timeout,opts.timeout)}req.send(body);function load(){if(timedOut){return}if(!support.timeout){clearTimeout(ontimeout)}var response=null;try{response=JSON.parse(req.responseText)}catch(e){}resolve({body:response,statusCode:req.status})}function error(event){if(timedOut){return}if(!support.timeout){clearTimeout(ontimeout)}reject(new Error("Could not connect to host, error was:"+event))}function timeout(){if(!support.timeout){timedOut=true;req.abort()}resolve(new Error("Timeout - Could not connect to endpoint "+url))}})}request.fallback=function(url,opts){return new Promise(function(resolve,reject){JSONPRequest(url,opts,function JSONPRequestDone(err,content){if(err){reject(err);return}resolve(content)})})};request.reject=function(val){return Promise.reject(val)};request.resolve=function(val){return Promise.resolve(val)};request.delay=function(ms){return new Promise(function(resolve){setTimeout(resolve,ms)})};require("./migration-layer")("algoliasearch")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./create-algoliasearch":4,"./jsonp-request":5,"./migration-layer":6,"es6-promise":2}]},{},[]);var algoliasearch=require("algoliasearch");var client=algoliasearch("latency","6be0576ff61c053d5f9a3225e2a90f76",{protocol:"http:"});var query="ab";client.startQueriesBatch();client.addQueryInBatch("contacts",query,{hitsPerPage:3});client.addQueryInBatch("contacts",query,{hitsPerPage:5});client.sendQueriesBatch(searchMultiCallback);function searchMultiCallback(err,content){if(err){console.error(err);return}var log=document.body.appendChild(document.createElement("div"));log.innerHTML="";var contacts=content.results[0];for(var i=0;i<contacts.hits.length;++i){log.innerHTML+=JSON.stringify(contacts.hits[i])}var products=contacts.results[1];for(var i=0;i<contacts.hits.length;++i){log.innerHTML+=JSON.stringify(contacts.hits[i])}} |
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": { | |
| "algoliasearch": "3.0.1" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment