UNPKG

xe-ajax-mock

Version:
6 lines 12.8 kB
/** * xe-ajax-mock.js v1.12.0 * MIT License. * @preserve */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.XEAjaxMock=e()}(this,function(){"use strict";var e=Object.prototype.toString,t=[{rules:[["yyyy",4],["yyy",3],["yy",2]]},{rules:[["MM",2],["M",1]],offset:-1},{rules:[["dd",2],["d",1]]},{rules:[["HH",2],["H",1]]},{rules:[["mm",2],["m",1]]},{rules:[["ss",2],["s",1]]},{rules:[["SSS",3],["SS",2],["S",1]]}],h={isArray:Array.isArray||function(t){return"[object Array]"===e.call(t)},isDate:function(t){return"[object Date]"===e.call(t)},isObject:function(t){return"object"==typeof t},isFunction:function(t){return"function"==typeof t},isString:function(t){return"string"==typeof t},getRandom:function(t,e){return e<=t?t:(t=t||0)+Math.round(Math.random()*((e||9)-t))},toStringDate:function(i,a){if(i){if(h.isDate(i))return i;if(!isNaN(i))return new Date(i);if(h.isString(i)){a=a||"yyyy-MM-dd HH:mm:ss.SSS";var u=[];return h.arrayEach(t,function(t){for(var e,n,r=0,o=t.rules,s=o.length;r<s;r++){if(e=o[r],-1<(n=a.indexOf(e[0]))){u.push(parseFloat(i.substring(n,n+e[1])||0)+(t.offset||0));break}r===s-1&&u.push(0)}}),new Date(u[0],u[1],u[2],u[3],u[4],u[5],u[6])}}return"Invalid Date"},toDateString:function(e,t){if(e=h.toStringDate(e),h.isDate(e)){var n=["日","一","二","三","四","五","六"],r={"q+":Math.floor((e.getMonth()+3)/3),"M+":e.getMonth()+1,"E+":e.getDay(),"d+":e.getDate(),"H+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),S:e.getMilliseconds()},o=String(t||"yyyy-MM-dd HH:mm:ss").replace(/(y+)/,function(t){return(""+e.getFullYear()).substr(4-t.length)});for(var s in r)if(r.hasOwnProperty(s)){var i=""+r[s];o=o.replace(new RegExp("("+s+")"),function(t){return"q+"===s||"E+"===s?n[i]:1===t.length?i:("00"+i).substr(i.length)})}return o}return e},getHeaderObjs:function(t){if(t&&t.forEach){var n={};return t.forEach(function(t,e){n[e]=t}),n}return t||{}},objectAssign:Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])e.hasOwnProperty(o)&&(t[o]=e[o]);return t},arrayEach:function(t,e,n){if(t.forEach)return t.forEach(e,n);for(var r=0,o=t.length||0;r<o;r++)e.call(n||this,t[r],r,t)},arrayFind:function(t,e,n){if(t.find)return t.find(e,n);for(var r=0,o=t.length||0;r<o;r++)if(e.call(n||this,t[r],r,t))return t[r]},objectEach:function(t,e,n){for(var r in t)t.hasOwnProperty(r)&&e.call(n||this,t[r],r,t)},objectKeys:function(t){var n=[];if(t){if(Object.keys)return Object.keys(t);h.objectEach(t,function(t,e){n.push(e)})}return n},objectValues:function(e){if(Object.values)return e?Object.values(e):[];var n=[];return h.arrayEach(h.objectKeys(e),function(t){n.push(e[t])}),n},arrayShuffle:function(t){for(var e=[],n=h.objectValues(t),r=n.length-1;0<=r;r--){var o=0<r?h.getRandom(0,r):0;e.push(n[o]),n.splice(o,1)}return e},arraySample:function(t,e){var n=h.arrayShuffle(t);return 1===arguments.length?n[0]:(e<n.length&&(n.length=e||0),n)},getLocatOrigin:function(){return"undefined"==typeof location?"":location.origin||location.protocol+"//"+location.host},getBaseURL:function(){if("undefined"==typeof location)return"";var t=location.pathname,e=h.lastIndexOf(t,"/")+1;return h.getLocatOrigin()+(e===t.length?t:t.substring(0,e))},lastIndexOf:function(t,e){if(h.isFunction(t.lastIndexOf))return t.lastIndexOf(e);for(var n=t.length-1;0<=n;n--)if(e===t[n])return n;return-1},getScopeNumber:function(t){var e=String(t).match(/(\d+)-(\d+)/);return e&&3===e.length?h.getRandom(parseInt(e[1]),parseInt(e[2])):isNaN(t)?0:Number(t)}},s={baseURL:h.getBaseURL(),template:!1,pathVariable:!0,timeout:"20-400",headers:{"Content-Type":"application/json; charset=UTF-8"},error:!0,log:!1},c=[],r={random:{num:h.getRandom,time:function(t,e,n){return t?e?h.getRandom(h.toStringDate(t,n).getTime(),h.toStringDate(e,n).getTime()):h.toStringDate(t,n).getTime():t},date:function(t,e,n){return t?e?h.toDateString(r.random.time(t,e),n):h.toDateString(t,n):t},repeat:function(t,e,n){if(e=e||1,n=n||e,h.isString(t)&&(t=t.split("")),t.length<n){for(var r=t;r.length<n;)r=r.concat(t);r.length=n,t=r}return h.arraySample(t,h.getRandom(e,n)).join("")}}},o={tStart:"__restArr=[]",tEnd:"return __restArr.join('');",contStart:"__restArr.push('",contEnd:"');\n",contTrimEnd:"'.trim());\n",cStart:"__restArr.push(",cEnd:");\n",simplifyRegExp:/__restArr\.push\('\s*'\);/g};function f(t,e){var n=t.replace(/[\r\n\t]/g," ").replace(/{{\s*(.*?)\s*}}/g,function(t,e){return n=o.cStart+e+o.cEnd,o.contEnd+n+o.contStart;var n});try{return n="var "+o.tStart+";with(opts){"+o.contStart+n+o.contEnd+"};"+o.tEnd,new Function("opts",n.replace(o.simplifyRegExp,""))(e)}catch(t){console.error(t)}return t}var l=/(.+)\|(array|random)\((.+)\)$/;function i(t,e){var n=null;if(n=p(t,new g({},e)),h.isObject(n)){var r=h.objectKeys(n);1!==r.length||"!return"!==r[0]&&"~"!==r[0]||(n=n[r[0]])}return n}function p(t,e){if(t){if(h.isArray(t))return d(t,e);if(h.isObject(t))return n=t,u=e,c={},h.objectEach(n,function(t,e){var n=e.match(l),r=null;if(n&&4===n.length){e=n[1];var o="random"===n[2].toLowerCase();if("array"===n[2].toLowerCase()||o){var s=h.getScopeNumber(f(n[3],u));if(h.isArray(t))t.length>s?(r=d(o?h.arraySample(t,s):t.slice(0,s),u),o&&1===r.length&&(r=r[0])):r=d(t,u);else{r=[];for(var i=0;i<s;i++){var a=new g({$parent:u,$obj:r,$value:null,$size:s,$index:i},u.$fns);r.push(p(t,a))}}}}else r=p(t,u),(n=e.match(/(.+)\|(number|boolean)$/))&&3===n.length&&(e=n[1],"number"===n[2].toLowerCase()?r=parseFloat(r):"boolean"===n[2].toLowerCase()&&(r="0"!==r&&Boolean(r)));c[e]=r}),c;if(h.isString(t))return f(t,e)}var n,u,c;return t}function d(r,o){var s=[];return h.arrayEach(r,function(t,e){var n=new g({$parent:o,$obj:r,$value:t,$size:r.length,$index:e},o.$fns);s.push(p(t,n))}),s}function g(t,e){this.$fns=e,h.objectAssign(this,e,t)}function n(){this._mock=null,this._xhr=null}i.mixin=function(t){return h.objectAssign(g.prototype,t)},i.mixin(r),h.objectAssign(n.prototype,{timeout:0,status:0,readyState:0,ontimeout:null,onreadystatechange:null,withCredentials:!1,response:"",responseText:"",upload:{},open:function(t,e){this._mock=M.mateMockItem(this._request),this._mock?(this.readyState=1,h.isFunction(this.onreadystatechange)&&this.onreadystatechange()):(this._xhr=new XMLHttpRequest,this._xhr.open(t,e,!0))},send:function(t){var e=this,n=this._mock,r=this._request;if(n)return M.getMockResponse(r,n).then(function(t){e.readyState=4,e._updateResponse(r,t),e._triggerEvent("readystatechange"),e._triggerEvent("load"),M.outMockLog(r,t,n)});var o=this._xhr;o.withCredentials=this.withCredentials,o.responseType=this.responseType||"",o.onload=function(){e._triggerEvent("load")},o.onerror=function(){e._triggerEvent("error")},o.ontimeout=function(){e._triggerEvent("timeout")},o.onabort=function(){e._triggerEvent("abort")},o.onreadystatechange=function(){e.readyState=o.readyState,e._updateResponse(r,{status:o.status,body:o.response}),e._triggerEvent("readystatechange")};var s=this.upload;s.onprogress&&o.upload&&(o.upload.onprogress=s.onprogress),o.send(t)},abort:function(){var e=this,n=this._mock,r=this._request;setTimeout(function(){if(n){if(0!==e.readyState){clearTimeout(n._waitingTimeout);var t={status:0,body:""};e._updateResponse(e._request,t),e.readyState=4,e._triggerEvent("timeout"),e.readyState=0,M.outMockLog(r,t,n)}}else e._xhr&&e._xhr.abort()})},setRequestHeader:function(t,e){this._xhr&&this._xhr.setRequestHeader(t,e)},getAllResponseHeaders:function(){if(this._xhr)return this._xhr.getAllResponseHeaders();var t="",e=this._headers;if(e)for(var n in e)e.hasOwnProperty(n)&&(t+=n+": "+e[n]+"\n");return t},_triggerEvent:function(t){h.isFunction(this["on"+t])&&this["on"+t]({type:t})},_updateResponse:function(t,e){var n=e.body||"";this.status=e.status,this._headers=e.headers,this._mock&&(h.isString(n)||(n=JSON.stringify(n))),"blob"===this.responseType?(this.response=n instanceof Blob?n:new Blob([n]),this.responseText=""):this.responseText=this.response=n}});var a={XEXMLHttpRequest:n};var u={sendJsonp:function(t,e){var n=e._request,r=M.mateMockItem(n);return r?M.getMockResponse(n,r).then(function(t){return M.outMockLog(n,t,r),t}):self.fetch(t,e)}},m="undefined"==typeof window?this:window;function y(e){e.script.parentNode===document.body&&document.body.removeChild(e.script);try{delete m[e.jsonpCallback]}catch(t){m[e.jsonpCallback]=void 0}}function b(t,e,n){y(t),n(e)}function v(t,e){y(t),e(new TypeError("JSONP request failed"))}var S={sendJsonp:function(o,s){return new Promise(function(e,n){var t,r=M.mateMockItem(s);if(m[s.jsonpCallback]=function(t){b(s,{status:200,body:t},e)},r)return M.getMockResponse(s,r).then(function(t){t.status<200||300<=t.status?v(s,n):b(s,t.body,e),M.outMockLog(s,t,r)});t=s.getUrl(),o.type="text/javascript",o.src=t+(-1===t.indexOf("?")?"?":"&")+s.jsonp+"="+s.jsonpCallback,o.onerror=function(){v(s,n)},s.timeout&&setTimeout(function(){v(s,n)},s.timeout),document.body.appendChild(o)})}},j={};function E(t,e){try{return JSON.parse(j[e])}catch(t){}return j[e]}function w(t,e,n,r){var o=t.context.options;n&&!0===o.template&&(n=i(n,{$pathVariable:t.pathVariable,$params:e.params||{},$body:e.body||{}})),n&&void 0!==n.body&&void 0!==n.status?(n.headers=h.objectAssign({},o.headers,n.headers),h.objectAssign(this,n)):(this.status=r,this.body=n,this.headers=h.objectAssign({},o.headers))}function _(t,e,n){this.request=t,this.pathVariable=n,this.context=e,this.waiting=h.getScopeNumber(e.options.timeout),this._waitingTimeout=null}function x(t,e,n,r){var o=n.statusText;this.Headers={General:{"Request URL":t,"Request Method":e.method,"Status Code":n.status+(o?" "+o:"")},"Response Headers":h.getHeaderObjs(n.headers),"Request Headers":h.getHeaderObjs(e.headers)},e.body&&(this.Headers["json-data"===e.bodyType?"Request Payload":"Form Data"]=e.body),e.params&&(this.Headers["Query String Parameters"]=e.params),this.Response=n.body,this.Timing={Waiting:r.waiting+" ms"}}function R(t,e){if(t&&"auto"===e.options.pathVariable){if(!isNaN(t))return parseFloat(t);if("true"===t)return!0;if("false"===t)return!1}return t}h.objectAssign(w.prototype,{require:function(r){return new Promise(function(t,e){if(0===r.indexOf("/")?r=h.getLocatOrigin()+r:/\w+:\/{2}.*/.test(r)||(r=s.baseURL.replace(/\/$/,"")+"/"+r),j[r])t(E(0,r));else{var n=new XMLHttpRequest;n.open("GET",r,!0),n.onreadystatechange=function(){4===n.readyState&&(n.status<200&&300<=n.status&&s.error&&console.error("This relative module was not found: "+r),j[r]=n.responseText,t(E(0,r)))},n.send()}})}});var M={outMockLog:function(t,e,n){var r=t.getUrl(),o=n.context.options,s=t.method,i=e.status<200||300<=e.status;i&&o.error&&console.error(["[Mock]",s,r,e.status].join(" ")),(i||o.log)&&(console.log(["[Mock]",i?"failed":"finished","loading:",s,r].join(" ")),console.info(new x(r,t,e,n)))},getMockResponse:function(r,o){var t=o.context;return new Promise(function(e,n){o._waitingTimeout=setTimeout(function(){if(!r.$complete)return h.isFunction(t.response)?Promise.resolve(t.response(r,new w(o,r,null,200),o)).then(function(t){e(new w(o,r,t,200))}):Promise.resolve(t.response).then(function(t){e(new w(o,r,t,200))}).catch(function(t){n(new w(o,r,t,500))})},o.waiting)})},mateMockItem:function(t){for(var e,n,r,o={},s=(t.getUrl()||"").split(/\?|#/)[0],i=0,a=c.length;i<a;i++)if((!(e=c[i]).jsonp||e.jsonp===t.jsonp)&&t.method.toLowerCase()===e.method.toLowerCase()&&(n=[],(r=s.match(new RegExp(e.path.replace(/{[^{}]+}/g,function(t){return n.push(t.substring(1,t.length-1)),"([^/]+)"}).replace(/\/[*]{2}/g,"/.+").replace(/\/[*]{1}/g,"/[^/]+")+"/?$")))&&r.length===n.length+1)){if(e.options.pathVariable&&n.length)for(var u=0;u<n.length;u++)o[n[u]]=R(r[u+1],e);return new _(t,e,o)}}};function T(t,e,n,r){var o=h.objectAssign({},s,r);return function e(t,n,r,o){h.isArray(t)&&h.arrayEach(t,function(t){t.path&&(o&&0===t.path.indexOf("/")?t.path=h.getLocatOrigin()+t.path:o&&!/\w+:\/{2}.*/.test(t.path)&&(t.path=r.replace(/\/$/,"")+"/"+t.path.replace(/^\//,"")),void 0!==t.response&&(t.method=String(t.method||"GET"),c.push(new O(t.path,t.method,t.response,n))),e(t.children,n,t.path))})}(h.isArray(t)?t:[{path:t,method:e,response:n}],o,o.baseURL,!0),T}function O(t,e,n,r){t&&e?(this.path=t,this.method=e,this.response=n,this.options=r):this.options.error&&console.error("path and method cannot be empty")}function A(r){return function(t,e,n){return T(t,r,e,n)}}T.setup=function(t){return h.objectAssign(s,t)},T.install=function(t){t.setup({$fetch:u.sendJsonp,$XMLHttpRequest:a.XEXMLHttpRequest,$jsonp:S.sendJsonp})},T.mixin=function(t){return h.objectAssign(T,t)};var k={template:i,Mock:T,JSONP:function(t,e,n){return T(t,"GET",e,h.objectAssign({jsonp:"callback"},n))},GET:A("GET"),POST:A("POST"),PUT:A("PUT"),DELETE:A("DELETE"),PATCH:A("PATCH"),HEAD:A("HEAD")};return T.mixin(k),T});