-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrestclient-min.js
27 lines (27 loc) · 12 KB
/
restclient-min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var RCBase64={keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(a){var b="",c,d,f,e,h,g,k=0;for(a=this.utf8_encode(a);k<a.length;)c=a.charCodeAt(k++),d=a.charCodeAt(k++),f=a.charCodeAt(k++),e=c>>2,c=(c&3)<<4|d>>4,h=(d&15)<<2|f>>6,g=f&63,isNaN(d)?h=g=64:isNaN(f)&&(g=64),b=b+this.keyStr.charAt(e)+this.keyStr.charAt(c)+this.keyStr.charAt(h)+this.keyStr.charAt(g);return b},decode:function(a){var b="",c,d,f,e,h,g=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");g<a.length;)c=
this.keyStr.indexOf(a.charAt(g++)),d=this.keyStr.indexOf(a.charAt(g++)),e=this.keyStr.indexOf(a.charAt(g++)),h=this.keyStr.indexOf(a.charAt(g++)),c=c<<2|d>>4,d=(d&15)<<4|e>>2,f=(e&3)<<6|h,b+=String.fromCharCode(c),64!==e&&(b+=String.fromCharCode(d)),64!==h&&(b+=String.fromCharCode(f));return b=this.utf8_decode(b)},utf8_encode:function(a){a=a.replace(/\r\n/g,"\n");var b="",c,d;for(c=0;c<a.length;c++)d=a.charCodeAt(c),128>d?b+=String.fromCharCode(d):(127<d&&2048>d?b+=String.fromCharCode(d>>6|192):(b+=
String.fromCharCode(d>>12|224),b+=String.fromCharCode(d>>6&63|128)),b+=String.fromCharCode(d&63|128));return b},utf8_decode:function(a){for(var b="",c=0,d=0,f=0,e=0;c<a.length;)d=a.charCodeAt(c),128>d?(b+=String.fromCharCode(d),c++):191<d&&224>d?(f=a.charCodeAt(c+1),b+=String.fromCharCode((d&31)<<6|f&63),c+=2):(f=a.charCodeAt(c+1),e=a.charCodeAt(c+2),b+=String.fromCharCode((d&15)<<12|(f&63)<<6|e&63),c+=3);return b}},RestClient;
RestClient=function(){this.VERSION="0.1.9";this.authorization={};this.server={};this.response={};this.headers={};this.accessToken={};this.autoStoreAccessToken=this.autoUseRefreshToken=!0;this.authorizationType="none";this.contentType="application/json";this.sendOAuthBearerAuthorization=!1;this.dataType="json";this.oauth2NeedsAuthorization=!0;this.expiredAccessTokenMessage="";this.restfulBehavior=!0;this.acceptType=this.backupAJAXURL=null;this.RESTMethods={create:"POST",read:"GET",update:"PUT","delete":"DELETE"};
this.OAUTH2GrantTypes={code:"authorization_code",implicit:"token",user:"password",client:"client_credentials",refresh:"refresh_token"};RestClient.prototype.initObject.call(this)};RestClient.prototype.HTTP_SUCCESS=["200","201","202","204","207"];RestClient.prototype.HTTP_BAD_REQUEST=400;RestClient.prototype.HTTP_UNAUTHORIZED=401;RestClient.prototype.OAUTH2_INVALID_GRANT="invalid_grant";
RestClient.prototype.initObject=function(){this.authorization={};this.server={};this.response={};this.headers={};this.accessToken={};this.autoStoreAccessToken=this.autoUseRefreshToken=!0;this.authorizationType="none";this.acceptType=this.contentType="application/json";this.sendOAuthBearerAuthorization=!1;this.oauth2NeedsAuthorization=!0;this.dataType="json";this.expiredAccessTokenMessage="The access token provided has expired."};
RestClient.prototype.setUseRefreshTokenAutomatically=function(a){_.isBoolean(a)&&(this.autoUseRefreshToken=a);return this};RestClient.prototype.setStoreAccessTokenAutomatically=function(a){_.isBoolean(a)&&(this.autoStoreAccessToken=a);return this};RestClient.prototype.setAuthorizationType=function(a){({none:1,basic:1,oauth2:1})[a]&&(this.authorizationType=a);return this};RestClient.prototype.setContentType=function(a){this.contentType=a;return this};
RestClient.prototype.setAcceptType=function(a){var b={plain:"text/plain",xhtml_xml:"application/xhtml+xml",json:"application/json",xml:"application/xml",all:"*/*"};b[a]&&(this.acceptType=b[a]);return this};RestClient.prototype.setSendBearerAuthorization=function(a){_.isBoolean(a)&&(this.sendOAuthBearerAuthorization=a);return this};RestClient.prototype.setOAuth2NeedsAuthorization=function(a){_.isBoolean(a)&&(this.oauth2NeedsAuthorization=a);return this};
RestClient.prototype.setDataType=function(a){var b={json:"application/json",plain:"text/plain",form:"application/x-www-form-urlencoded",html:"text/html"};b[a]&&(this.dataType=a,this.contentType=b[a]);return this};RestClient.prototype.setAccessTokenExpiredMessage=function(a){this.expiredAccessTokenMessage=a;return this};RestClient.prototype.getVersion=function(){return this.VERSION};
RestClient.prototype.setClient=function(a,b,c){this.authorization.client_id=a;this.authorization.client_secret=b;this.authorization.client_url="undefined"!==c?c:null;return this};RestClient.prototype.setGrantType=function(a,b){this.authorization.grant_type="undefined"!==this.OAUTH2GrantTypes[a]?this.OAUTH2GrantTypes[a]:null;this.authorization=_.extend(this.authorization,b);return this};
RestClient.prototype.setAuthorizationServer=function(a){var b=!0,c;"undefined"===typeof a||null===a?b=!1:(c=/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/,a.match(c)?this.server.rest_auth_uri=a:b=!1);return b};RestClient.prototype.setHeader=function(a,b){var c=!0,d;a&&b?(d=JSON.parse('{"'+a+'" : "'+b+'"}'),this.headers=_.extend(this.headers,d)):c=!1;return c};RestClient.prototype.JSONParse=function(a){var b;try{b=a?""===a?"":JSON.parse(a):""}catch(c){b="ERROR_PARSE"}return b};
RestClient.prototype.setBasicCredentials=function(a,b){this.authorization.basic_user=a;this.authorization.basic_password=b;return this};RestClient.prototype.setAccessToken=function(a){"object"===typeof a&&(this.accessToken=a);return this};RestClient.prototype.setRestfulBehavior=function(a){_.isBoolean(a)&&(this.restfulBehavior=a);return this};RestClient.prototype.setBackupAjaxUrl=function(a){this.backupAJAXURL=a;return this};
RestClient.prototype.toParams=function(a){var b=_.keys(a),c=[];_.each(b,function(b){c.push(b+"="+a[b])});return c.join("&")};RestClient.prototype.prepareBody=function(a){var b="";"json"===this.dataType||"jsonp"===this.dataType?"object"===typeof a&&(b=JSON.stringify(a)):b=this.toParams(a);return b};
RestClient.prototype.createXHR=function(){var a;if(window.XMLHttpRequest)a=new XMLHttpRequest;else try{a=new ActiveXObject("MSXML2.XMLHTTP")}catch(b){try{a=new ActiveXObject("Microsoft.XMLHTTP")}catch(c){}}return!a?!1:a};
RestClient.prototype.authorize=function(a){var b=this,c=!1,d=this.RESTMethods.create,f,e,h;f=RCBase64.encode(this.authorization.client_id+":"+this.authorization.client_secret);e=this.createXHR();try{e.open(d,this.server.rest_auth_uri,!1)}catch(g){return a.xhrfailure?a.xhrfailure(g,{}):this.XHRFailure(g,{}),c}e.onreadystatechange=function(){a.ready?a.ready(e):b.AuthorizeReady(e);if(4===e.readyState){h=b.JSONParse(e.responseText);if(-1!=b.HTTP_SUCCESS.indexOf(String(e.status))&&"ERROR_PARSE"!==h)if(b.autoStoreAccessToken&&
(b.accessToken=h.token||{}),c=!0,a.success)try{a.success(e,h)}catch(d){throw Error(d.message);}else b.AuthorizeSuccess(e,h);else if("ERROR_PARSE"===h&&(h={success:!1,error:{error:b.HTTP_BAD_REQUEST,error_description:"Response is not a valid JSON"}}),a.failure)try{a.failure(e,h)}catch(f){throw Error(f.message);}else b.AuthorizeFailure(e,h);"function"===typeof a.complete&&a.complete(e,h)}};d={};if(this.authorization.grant_type)switch(d.grant_type=this.authorization.grant_type,this.authorization.grant_type){case "authorization_code":d.code=
this.authorization.code;break;case "token":d.token=this.authorization.token;break;case "password":d.username=this.authorization.username;d.password=this.authorization.password;break;case "client_credentials":d.client_id=this.authorization.client_id;d.client_id=this.authorization.client_secret;break;case "refresh_token":d.refresh_token=this.authorization.refresh_token}this.oauth2NeedsAuthorization&&e.setRequestHeader("Authorization","Basic "+f);e.setRequestHeader("Accept",this.acceptType);e.setRequestHeader("Content-Type",
this.contentType);_.each(this.headers,function(a,b){e.setRequestHeader(b,a)});e.send(this.prepareBody(d));return c};RestClient.prototype.prepareReqFields=function(a){return{success:!1,error:{error:this.HTTP_BAD_REQUEST,error_description:"Required fields not found"},fields:a}};
RestClient.prototype.prepareConsumeUrl=function(a,b,c,d){var f,e,h=this.acceptType,g=this.contentType,k=!1;if(this.restfulBehavior)switch(a){case "read":f=b;c&&(f+=c);"oauth2"===this.authorizationType&&!this.sendOAuthBearerAuthorization&&(k=!0,f+="?access_token="+this.accessToken.access_token);d&&d!=={}&&(f=(k?f+"&":f+"?")+this.toParams(d));e=null;null===g&&(g="application/json");break;case "create":f=b;e=d||{};"oauth2"===this.authorizationType&&!this.sendOAuthBearerAuthorization&&(e.access_token=
this.accessToken.access_token);e=this.prepareBody(e);break;case "update":f=b;c&&(f+=c);e=d||{};"oauth2"===this.authorizationType&&!this.sendOAuthBearerAuthorization&&(e.access_token=this.accessToken.access_token);e=this.prepareBody(e);break;case "delete":f=b,c&&(f+=c),e=d||{},"oauth2"===this.authorizationType&&!this.sendOAuthBearerAuthorization&&(e.access_token=this.accessToken.access_token),e=this.prepareBody(e)}else f=this.backupAJAXURL,e={operation:a,url:b,id:c,data:d},e="data='"+encodeURIComponent(JSON.stringify(e))+
"'",null===g&&(g="application/json");h||(h="*/*");return{url:f,body:e,content_type:g,acceptType:h}};RestClient.prototype.getCall=function(a){a.operation="read";return this.consume(a)};RestClient.prototype.postCall=function(a){a.operation="create";return this.consume(a)};RestClient.prototype.putCall=function(a){a.operation="update";return this.consume(a)};RestClient.prototype.deleteCall=function(a){a.operation="delete";return this.consume(a)};
RestClient.prototype.consume=function(a){var b,c,d,f={},e,h,g,k=!0,l=[],n,m,p,q,r=!1;a.operation?d=a.operation:(k=!1,l.push("operation"));a.url?e=a.url:(k=!1,l.push("url"));n=a.data||null;h=a.id||null;if(!k)return a.failure?a.failure(null,this.prepareReqFields(l)):this.ConsumeFailure(null,this.prepareReqFields(l)),k;m=this.prepareConsumeUrl(d,e,h,n);h=m.url;e=m.body;q=m.content_type;m=m.acceptType;c=this.createXHR();d=this.restfulBehavior?this.RESTMethods[d]:this.RESTMethods.create;try{switch(c.open(d,
h,!1),this.authorizationType){case "basic":b=RCBase64.encode(this.authorization.basic_user+":"+this.authorization.basic_password);c.setRequestHeader("Authorization","Basic "+b);break;case "oauth2":if(this.accessToken.access_token)this.sendOAuthBearerAuthorization&&(p="Bearer "+this.accessToken.access_token,c.setRequestHeader("Authorization",p));else return k=!1,l.push("access_token"),a.failure?a.failure(null,this.prepareReqFields(l)):this.ConsumeFailure(null,this.prepareReqFields(l)),k}}catch(s){return a.xhrfailure?
a.xhrfailure(s,n):this.XHRFailure(s,n),!1}g=this;c.onreadystatechange=function(){a.ready?a.ready(c):g.ConsumeReady(c);if(4===c.readyState){f=g.JSONParse(c.responseText);if(-1!=g.HTTP_SUCCESS.indexOf(String(c.status))&&"ERROR_PARSE"!==f)if(g.autoStoreAccessToken&&(g.accessToken=f.token||{}),k=!0,a.success)try{a.success(c,f)}catch(b){throw Error(b.message);}else g.AuthorizeSuccess(c,f);else if(k=!1,"ERROR_PARSE"===f?f={success:!1,error:{error:g.HTTP_BAD_REQUEST,error_description:"Response is not a valid JSON"}}:
(f.error===g.OAUTH2_INVALID_GRANT&&f.error_description===g.expiredAccessTokenMessage&&(r=!0),c.status===g.HTTP_UNAUTHORIZED&&(g.autoUseRefreshToken&&r)&&(g.accessToken.refresh_token?(g.setGrantType("refresh",{refresh_token:g.accessToken.refresh_token}),g.authorize({success:function(b,c){(k=g.consume(a))&&(a.autorefresh?a.autorefresh(g.accessToken):g.AuthorizeAutoRefresh(g.accessToken))},failure:function(b,c){k=!1;a.failure?a.failure(null,c):g.ConsumeFailure(null,c)}})):(k=!1,f={success:!1,error:{error:g.HTTP_UNAUTHORIZED,
error_description:"Refresh token is not defined"}}))),a.failure)try{a.failure(c,f)}catch(d){throw Error(d.message);}else g.AuthorizeFailure(c,f);"function"===typeof a.complete&&a.complete(c,f)}};c.setRequestHeader("Accept",m);c.setRequestHeader("Content-Type",q);_.each(this.headers,function(a,b){c.setRequestHeader(b,a)});c.send(e);return k};RestClient.prototype.XHRFailure=function(a,b){};RestClient.prototype.AuthorizeSuccess=function(a,b){};RestClient.prototype.AuthorizeFailure=function(a,b){};
RestClient.prototype.AuthorizeReady=function(a){};RestClient.prototype.AuthorizeAutoRefresh=function(a){};RestClient.prototype.ConsumeSuccess=function(a,b){};RestClient.prototype.ConsumeFailure=function(a,b){};RestClient.prototype.ConsumeReady=function(a){};if("undefined"!==typeof exports){module.exports={RestClient:RestClient,RCBase64:RCBase64};var _=require("underscore")};