@microlink/mql
Advanced tools
Comparing version 0.5.23 to 0.6.0
@@ -5,2 +5,9 @@ # Changelog | ||
## [0.6.0](https://github.com/microlinkhq/mql/compare/v0.5.23...v0.6.0) (2020-03-01) | ||
### Features | ||
* better error handling ([17bee3b](https://github.com/microlinkhq/mql/commit/17bee3b051803f21ac761967439b2fcd4fe8d409)) | ||
### [0.5.23](https://github.com/microlinkhq/mql/compare/v0.5.22...v0.5.23) (2020-02-28) | ||
@@ -7,0 +14,0 @@ |
@@ -937,3 +937,3 @@ (function (global, factory) { | ||
const fetchFromApi = async (url, apiUrl, opts = {}) => { | ||
const fetchFromApi = async (apiUrl, opts = {}) => { | ||
try { | ||
@@ -945,14 +945,17 @@ const response = await got(apiUrl, opts); | ||
const { name, message: rawMessage, response = {} } = err; | ||
const { statusCode = 500, body: rawBody } = response; | ||
const { statusCode = 500, body: rawBody, headers, url: uri = apiUrl } = response; | ||
const retryTime = Number((opts.retry * opts.timeout).toFixed(0)); | ||
const isClientError = name === 'TimeoutError'; | ||
if (isTimeoutError(err, statusCode)) { | ||
const message = `The \`url\` as \`${url}\` reached timeout after ${opts.retry.maxRetryAfter}ms.`; | ||
const message = `The request reached timeout after ${retryTime}ms.`; | ||
throw new MicrolinkError({ | ||
url, | ||
url: uri, | ||
data: { url: message }, | ||
status: 'fail', | ||
code: name === 'TimeoutError' ? 'ETIMEOUTCLIENT' : 'ETIMEOUT', | ||
code: isClientError ? 'ETIMEOUTCLIENT' : 'ETIMEOUT', | ||
message, | ||
more: 'https://microlink.io/docs/api/api-parameters/url', | ||
statusCode | ||
more: `https://microlink.io/${isClientError ? 'etimeoutclient' : 'etimeout'}`, | ||
statusCode, | ||
headers | ||
}) | ||
@@ -967,9 +970,8 @@ } | ||
const message = body.data ? body.data[Object.keys(body.data)[0]] : body.message; | ||
throw MicrolinkError({ | ||
...body, | ||
message, | ||
url, | ||
statusCode | ||
message: body.message, | ||
url: uri, | ||
statusCode, | ||
headers | ||
}) | ||
@@ -986,3 +988,3 @@ } | ||
isStream = false, | ||
retry = 4, | ||
retry = 3, | ||
timeout = 30000, | ||
@@ -1009,3 +1011,3 @@ responseType = 'json', | ||
const [apiUrl, fetchOpts] = getApiUrl(url, opts); | ||
return fetchFromApi(url, apiUrl, { ...opts, ...fetchOpts }) | ||
return fetchFromApi(apiUrl, { ...opts, ...fetchOpts }) | ||
}; | ||
@@ -1056,3 +1058,3 @@ | ||
flatten: flat, | ||
VERSION: '0.5.23' | ||
VERSION: '0.6.0' | ||
}); | ||
@@ -1059,0 +1061,0 @@ |
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("url")):"function"==typeof define&&define.amd?define(["url"],e):(t=t||self).mql=e(t.url)}(this,(function(t){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t;var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(t){return t&&t.default||t}var o=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t,r){t.exports=function(){ | ||
/*! MIT License © Sindre Sorhus */ | ||
const t={},r=t=>"undefined"!=typeof self&&self&&t in self?self:"undefined"!=typeof window&&window&&t in window?window:void 0!==e&&e&&t in e?e:"undefined"!=typeof globalThis&&globalThis?globalThis:void 0,o=["Headers","Request","Response","ReadableStream","fetch","AbortController","FormData"];for(const e of o)Object.defineProperty(t,e,{get(){const t=r(e),o=t&&t[e];return"function"==typeof o?o.bind(t):o}});const s=t=>null!==t&&"object"==typeof t,n="function"==typeof t.AbortController,i="function"==typeof t.ReadableStream,a=(...t)=>{let e={};for(const r of t)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(s(r))for(let[t,o]of Object.entries(r))s(o)&&Reflect.has(e,t)&&(o=a(e[t],o)),e={...e,[t]:o};return e},c=["get","post","put","patch","head","delete"],u={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},f=[413,429,503],p=Symbol("stop");class l extends Error{constructor(t){super(t.statusText),this.name="HTTPError",this.response=t}}class h extends Error{constructor(){super("Request timed out"),this.name="TimeoutError"}}const d=t=>new Promise(e=>setTimeout(e,t)),y=t=>c.includes(t)?t.toUpperCase():t,m={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:f},b=(t={})=>{if("number"==typeof t)return{...m,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...m,...t,afterStatusCodes:f}};class w{constructor(e,r={}){if(this._retryCount=0,this._input=e,this._options={credentials:this._input.credentials||"same-origin",...r,hooks:a({beforeRequest:[],beforeRetry:[],afterResponse:[]},r.hooks),method:y(r.method||this._input.method),prefixUrl:String(r.prefixUrl||""),retry:b(r.retry),throwHttpErrors:!1!==r.throwHttpErrors,timeout:void 0===r.timeout?1e4:r.timeout},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof t.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(n&&(this.abortController=new t.AbortController,this._options.signal&&this._options.signal.addEventListener("abort",()=>{this.abortController.abort()}),this._options.signal=this.abortController.signal),this.request=new t.Request(this._input,this._options),this._options.searchParams){const e=new URL(this.request.url);e.search=new URLSearchParams(this._options.searchParams),this.request=new t.Request(new t.Request(e,this.request),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type","application/json"),this.request=new t.Request(this.request,{body:this._options.body}));const o=async()=>{if(this._options.timeout>2147483647)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await d(1);let e=await this._fetch();for(const r of this._options.hooks.afterResponse){const o=await r(this.request,this._options,e.clone());o instanceof t.Response&&(e=o)}if(!e.ok&&this._options.throwHttpErrors)throw new l(e);if(this._options.onDownloadProgress){if("function"!=typeof this._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!i)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return this._stream(e.clone(),this._options.onDownloadProgress)}return e},s=this._options.retry.methods.includes(this.request.method.toLowerCase())?this._retry(o):o();for(const[t,e]of Object.entries(u))s[t]=async()=>{this.request.headers.set("accept",this.request.headers.get("accept")||e);const r=(await s).clone();return"json"===t&&204===r.status?"":r[t]()};return s}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof h)){if(t instanceof l){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}return.3*2**(this._retryCount-1)*1e3}return 0}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),2147483647);if(0!==r&&this._retryCount>0){await d(r);for(const t of this._options.hooks.beforeRetry)if(await t({request:this.request,options:this._options,error:e,response:e.response.clone(),retryCount:this._retryCount})===p)return;return this._retry(t)}if(this._options.throwHttpErrors)throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}return!1===this._options.timeout?t.fetch(this.request.clone()):(e=t.fetch(this.request.clone()),r=this._options.timeout,o=this.abortController,new Promise((t,s)=>{const n=setTimeout(()=>{o&&o.abort(),s(new h)},r);e.then(t).catch(s).then(()=>{clearTimeout(n)})}));var e,r,o}_stream(e,r){const o=Number(e.headers.get("content-length"))||0;let s=0;return new t.Response(new t.ReadableStream({start(t){const n=e.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:o},new Uint8Array),async function e(){const{done:i,value:a}=await n.read();i?t.close():(r&&(s+=a.byteLength,r({percent:0===o?0:s/o,transferredBytes:s,totalBytes:o},a)),t.enqueue(a),e())}()}}))}}const g=(...t)=>{for(const e of t)if((!s(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return a({},...t)},_=t=>{const e=(e,r)=>new w(e,g(t,r));for(const r of c)e[r]=(e,o)=>new w(e,g(t,o,{method:r}));return e.HTTPError=l,e.TimeoutError=h,e.create=t=>_(g(t)),e.extend=e=>_(g(t,e)),e.stop=p,e};return _()}()}));const s=e.window?window.URL:t.URL,n=/^https?:\/\//i;function i(t){if(!t)return"";var e=decodeURIComponent(t);return"false"!==e&&("true"===e||(0*+e==0?+e:e))}var a=Object.freeze({__proto__:null,encode:function(t,e){var r,o,s,n="";for(r in t)if(void 0!==(s=t[r]))if(Array.isArray(s))for(o=0;o<s.length;o++)n&&(n+="&"),n+=encodeURIComponent(r)+"="+encodeURIComponent(s[o]);else n&&(n+="&"),n+=encodeURIComponent(r)+"="+encodeURIComponent(s);return(e||"")+n},decode:function(t){for(var e,r,o={},s=t.split("&");e=s.shift();)void 0!==o[r=(e=e.split("=")).shift()]?o[r]=[].concat(o[r],i(e.shift())):o[r]=i(e.shift());return o}}),c=Object.freeze({__proto__:null,default:t=>t});const u=(t,e,r,o)=>{if("length"===r||"prototype"===r)return;const s=Object.getOwnPropertyDescriptor(t,r),n=Object.getOwnPropertyDescriptor(e,r);!f(s,n)&&o||Object.defineProperty(t,r,n)},f=function(t,e){return void 0===t||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},p=(t,e)=>`/* Wrapped ${t}*/\n${e}`,l=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),h=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name");var d=(t,e,{ignoreNonConfigurable:r=!1}={})=>{const{name:o}=t;for(const o of Reflect.ownKeys(e))u(t,e,o,r);return((t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)})(t,e),((t,e,r)=>{const o=""===r?"":`with ${r.trim()}() `,s=p.bind(null,o,e.toString());Object.defineProperty(s,"name",h),Object.defineProperty(t,"toString",{...l,value:s})})(t,e,o),t},y={isFunction:t=>"function"==typeof t,isString:t=>"string"==typeof t,composeErrorMessage:(t,e)=>`${t}, ${e}`,inherits:(t,e)=>{t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}};const{isFunction:m,composeErrorMessage:b}=y;var w=function(t,...e){Object.assign(t,...e),t.description=m(t.message)?t.message(t):t.message,t.message=t.code?b(t.code,t.description):t.description},g=r(c);const{isString:_}=y;var j=function(t,e){function r(r){const o=new t,s=_(r)?{message:r}:r;return w(o,e,s),o.stack=g(o.stack),o}return r.prototype=t.prototype,d(r,t),r};const{inherits:E}=y,R=/[^0-9a-zA-Z_$]/;var O=function(t){if("string"!=typeof t)throw new TypeError("Expected className to be a string");if(R.test(t))throw new Error("className contains invalid characters");function e(){Object.defineProperty(this,"name",{configurable:!0,value:t,writable:!0}),Error.captureStackTrace(this,this.constructor)}return E(e,Error),d(e,Error),e};const v=t=>(e,r)=>{const o=O(e||t.name);return j(o,r)};var T=v(Error),C=v(TypeError),S=v(RangeError),q=v(EvalError),x=v(SyntaxError),A=v(ReferenceError),k=v(URIError);T.type=C,T.range=S,T.eval=q,T.syntax=x,T.reference=A,T.uri=k; | ||
const t={},r=t=>"undefined"!=typeof self&&self&&t in self?self:"undefined"!=typeof window&&window&&t in window?window:void 0!==e&&e&&t in e?e:"undefined"!=typeof globalThis&&globalThis?globalThis:void 0,o=["Headers","Request","Response","ReadableStream","fetch","AbortController","FormData"];for(const e of o)Object.defineProperty(t,e,{get(){const t=r(e),o=t&&t[e];return"function"==typeof o?o.bind(t):o}});const s=t=>null!==t&&"object"==typeof t,n="function"==typeof t.AbortController,i="function"==typeof t.ReadableStream,a=(...t)=>{let e={};for(const r of t)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(s(r))for(let[t,o]of Object.entries(r))s(o)&&Reflect.has(e,t)&&(o=a(e[t],o)),e={...e,[t]:o};return e},c=["get","post","put","patch","head","delete"],u={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},f=[413,429,503],p=Symbol("stop");class l extends Error{constructor(t){super(t.statusText),this.name="HTTPError",this.response=t}}class h extends Error{constructor(){super("Request timed out"),this.name="TimeoutError"}}const d=t=>new Promise(e=>setTimeout(e,t)),y=t=>c.includes(t)?t.toUpperCase():t,m={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:f},b=(t={})=>{if("number"==typeof t)return{...m,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...m,...t,afterStatusCodes:f}};class w{constructor(e,r={}){if(this._retryCount=0,this._input=e,this._options={credentials:this._input.credentials||"same-origin",...r,hooks:a({beforeRequest:[],beforeRetry:[],afterResponse:[]},r.hooks),method:y(r.method||this._input.method),prefixUrl:String(r.prefixUrl||""),retry:b(r.retry),throwHttpErrors:!1!==r.throwHttpErrors,timeout:void 0===r.timeout?1e4:r.timeout},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof t.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(n&&(this.abortController=new t.AbortController,this._options.signal&&this._options.signal.addEventListener("abort",()=>{this.abortController.abort()}),this._options.signal=this.abortController.signal),this.request=new t.Request(this._input,this._options),this._options.searchParams){const e=new URL(this.request.url);e.search=new URLSearchParams(this._options.searchParams),this.request=new t.Request(new t.Request(e,this.request),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type","application/json"),this.request=new t.Request(this.request,{body:this._options.body}));const o=async()=>{if(this._options.timeout>2147483647)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await d(1);let e=await this._fetch();for(const r of this._options.hooks.afterResponse){const o=await r(this.request,this._options,e.clone());o instanceof t.Response&&(e=o)}if(!e.ok&&this._options.throwHttpErrors)throw new l(e);if(this._options.onDownloadProgress){if("function"!=typeof this._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!i)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return this._stream(e.clone(),this._options.onDownloadProgress)}return e},s=this._options.retry.methods.includes(this.request.method.toLowerCase())?this._retry(o):o();for(const[t,e]of Object.entries(u))s[t]=async()=>{this.request.headers.set("accept",this.request.headers.get("accept")||e);const r=(await s).clone();return"json"===t&&204===r.status?"":r[t]()};return s}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof h)){if(t instanceof l){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}return.3*2**(this._retryCount-1)*1e3}return 0}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),2147483647);if(0!==r&&this._retryCount>0){await d(r);for(const t of this._options.hooks.beforeRetry)if(await t({request:this.request,options:this._options,error:e,response:e.response.clone(),retryCount:this._retryCount})===p)return;return this._retry(t)}if(this._options.throwHttpErrors)throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}return!1===this._options.timeout?t.fetch(this.request.clone()):(e=t.fetch(this.request.clone()),r=this._options.timeout,o=this.abortController,new Promise((t,s)=>{const n=setTimeout(()=>{o&&o.abort(),s(new h)},r);e.then(t).catch(s).then(()=>{clearTimeout(n)})}));var e,r,o}_stream(e,r){const o=Number(e.headers.get("content-length"))||0;let s=0;return new t.Response(new t.ReadableStream({start(t){const n=e.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:o},new Uint8Array),async function e(){const{done:i,value:a}=await n.read();i?t.close():(r&&(s+=a.byteLength,r({percent:0===o?0:s/o,transferredBytes:s,totalBytes:o},a)),t.enqueue(a),e())}()}}))}}const g=(...t)=>{for(const e of t)if((!s(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return a({},...t)},_=t=>{const e=(e,r)=>new w(e,g(t,r));for(const r of c)e[r]=(e,o)=>new w(e,g(t,o,{method:r}));return e.HTTPError=l,e.TimeoutError=h,e.create=t=>_(g(t)),e.extend=e=>_(g(t,e)),e.stop=p,e};return _()}()}));const s=e.window?window.URL:t.URL,n=/^https?:\/\//i;function i(t){if(!t)return"";var e=decodeURIComponent(t);return"false"!==e&&("true"===e||(0*+e==0?+e:e))}var a=Object.freeze({__proto__:null,encode:function(t,e){var r,o,s,n="";for(r in t)if(void 0!==(s=t[r]))if(Array.isArray(s))for(o=0;o<s.length;o++)n&&(n+="&"),n+=encodeURIComponent(r)+"="+encodeURIComponent(s[o]);else n&&(n+="&"),n+=encodeURIComponent(r)+"="+encodeURIComponent(s);return(e||"")+n},decode:function(t){for(var e,r,o={},s=t.split("&");e=s.shift();)void 0!==o[r=(e=e.split("=")).shift()]?o[r]=[].concat(o[r],i(e.shift())):o[r]=i(e.shift());return o}}),c=Object.freeze({__proto__:null,default:t=>t});const u=(t,e,r,o)=>{if("length"===r||"prototype"===r)return;const s=Object.getOwnPropertyDescriptor(t,r),n=Object.getOwnPropertyDescriptor(e,r);!f(s,n)&&o||Object.defineProperty(t,r,n)},f=function(t,e){return void 0===t||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},p=(t,e)=>`/* Wrapped ${t}*/\n${e}`,l=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),h=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name");var d=(t,e,{ignoreNonConfigurable:r=!1}={})=>{const{name:o}=t;for(const o of Reflect.ownKeys(e))u(t,e,o,r);return((t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)})(t,e),((t,e,r)=>{const o=""===r?"":`with ${r.trim()}() `,s=p.bind(null,o,e.toString());Object.defineProperty(s,"name",h),Object.defineProperty(t,"toString",{...l,value:s})})(t,e,o),t},y={isFunction:t=>"function"==typeof t,isString:t=>"string"==typeof t,composeErrorMessage:(t,e)=>`${t}, ${e}`,inherits:(t,e)=>{t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}};const{isFunction:m,composeErrorMessage:b}=y;var w=function(t,...e){Object.assign(t,...e),t.description=m(t.message)?t.message(t):t.message,t.message=t.code?b(t.code,t.description):t.description},g=r(c);const{isString:_}=y;var j=function(t,e){function r(r){const o=new t,s=_(r)?{message:r}:r;return w(o,e,s),o.stack=g(o.stack),o}return r.prototype=t.prototype,d(r,t),r};const{inherits:E}=y,R=/[^0-9a-zA-Z_$]/;var O=function(t){if("string"!=typeof t)throw new TypeError("Expected className to be a string");if(R.test(t))throw new Error("className contains invalid characters");function e(){Object.defineProperty(this,"name",{configurable:!0,value:t,writable:!0}),Error.captureStackTrace(this,this.constructor)}return E(e,Error),d(e,Error),e};const v=t=>(e,r)=>{const o=O(e||t.name);return j(o,r)};var T=v(Error),C=v(TypeError),q=v(RangeError),S=v(EvalError),x=v(SyntaxError),A=v(ReferenceError),k=v(URIError);T.type=C,T.range=q,T.eval=S,T.syntax=x,T.reference=A,T.uri=k; | ||
/*! | ||
@@ -10,3 +10,3 @@ * Determine if an object is a Buffer | ||
*/ | ||
var P=function(t){return null!=t&&null!=t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)},U=D;function N(t){return t}function D(t,e){const r=(e=e||{}).delimiter||".",o=e.maxDepth,s=e.transformKey||N,n={};return function t(i,a,c){c=c||1,Object.keys(i).forEach((function(u){const f=i[u],p=e.safe&&Array.isArray(f),l=Object.prototype.toString.call(f),h=P(f),d="[object Object]"===l||"[object Array]"===l,y=a?a+r+s(u):s(u);if(!p&&!h&&d&&Object.keys(f).length&&(!e.maxDepth||c<o))return t(f,y,c+1);n[y]=f}))}(t),n}D.flatten=D,D.unflatten=function t(e,r){const o=(r=r||{}).delimiter||".",s=r.overwrite||!1,n=r.transformKey||N,i={};if(P(e)||"[object Object]"!==Object.prototype.toString.call(e))return e;function a(t){const e=Number(t);return isNaN(e)||-1!==t.indexOf(".")||r.object?t:e}return e=Object.keys(e).reduce((t,s)=>{const n=Object.prototype.toString.call(e[s]);return!("[object Object]"===n||"[object Array]"===n)||function(t){const e=Object.prototype.toString.call(t),r="[object Array]"===e,o="[object Object]"===e;if(!t)return!0;if(r)return!t.length;if(o)return!Object.keys(t).length}(e[s])?(t[s]=e[s],t):function(t,e,r){return Object.keys(r).reduce((function(e,s){return e[t+o+s]=r[s],e}),e)}(s,t,D(e[s],r))},{}),Object.keys(e).forEach((function(c){const u=c.split(o).map(n);let f=a(u.shift()),p=a(u[0]),l=i;for(;void 0!==p;){const t=Object.prototype.toString.call(l[f]),e="[object Object]"===t||"[object Array]"===t;if(!s&&!e&&void 0!==l[f])return;(s&&!e||!s&&null==l[f])&&(l[f]="number"!=typeof p||r.object?{}:[]),l=l[f],u.length>0&&(f=a(u.shift()),p=a(u[0]))}l[f]=t(e[c],r)})),i};const I={FREE:"https://api.microlink.io",PRO:"https://pro.microlink.io"};var L=({VERSION:t,MicrolinkError:e,isUrlHttp:r,stringify:o,got:s,flatten:n})=>{const i=t=>{if("object"!=typeof t)return;const e=n(t);return Object.keys(e).reduce((t,r)=>({...t,[`data.${r}`]:e[r]}),{})},a=async(t,r,o={})=>{try{const t=await s(r,o),{body:e}=t;return{...e,response:t}}catch(r){const{name:s,message:n,response:i={}}=r,{statusCode:a=500,body:c}=i;if(((t,e)=>"TimeoutError"===t.name||"HTTPError"===t.name&&"5"===e.toString()[0]||"invalid-json"===t.type)(r,a)){const r=`The \`url\` as \`${t}\` reached timeout after ${o.retry.maxRetryAfter}ms.`;throw new e({url:t,data:{url:r},status:"fail",code:"TimeoutError"===s?"ETIMEOUTCLIENT":"ETIMEOUT",message:r,more:"https://microlink.io/docs/api/api-parameters/url",statusCode:a})}const u=c?"string"==typeof c||Buffer.isBuffer(c)?JSON.parse(c):c:{message:n,status:"fail"},f=u.data?u.data[Object.keys(u.data)[0]]:u.message;throw e({...u,message:f,url:t,statusCode:a})}},c=(t,{data:e,apiKey:r,endpoint:s,isStream:a=!1,retry:c=4,timeout:u=3e4,responseType:f="json",...p}={})=>{const l=!!r;var h;return[`${s||I[l?"PRO":"FREE"]}?${o({url:t,...i(e),...n((h=p,Object.keys(h).forEach(t=>null==h[t]&&delete h[t]),h))})}`,{retry:c,timeout:u,responseType:f,isStream:a,headers:l?{"x-api-key":r}:{}}]},u=async(t,o={})=>{((t="")=>{if(!r(t)){const r=`The \`url\` as \`${t}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new e({url:t,data:{url:r},status:"fail",code:"EINVALURLCLIENT",message:r,more:"https://microlink.io/docs/api/api-parameters/url"})}})(t);const[s,n]=c(t,o);return a(t,s,{...o,...n})};return u.MicrolinkError=e,u.getApiUrl=c,u.fetchFromApi=a,u.mapRules=i,u.version=t,u.stream=(t,e)=>u(t,{...e,isStream:!0}),u},$=r(a);const H=o.default||o,{encode:M}=$;return L({MicrolinkError:T("MicrolinkError"),isUrlHttp:t=>{try{return n.test(new s(t).href)}catch(t){return!1}},stringify:M,got:async(t,{responseType:e,...r})=>{try{const e=await H(t,r),o=await e.json(),{headers:s,status:n,statusText:i}=e;return{url:e.url,body:o,headers:s,statusCode:n,statusMessage:i}}catch(t){if(t.response){const{response:e}=t;t.response={...e,statusCode:e.status,body:await e.json()}}throw t}},flatten:U,VERSION:"0.5.23"})})); | ||
var P=function(t){return null!=t&&null!=t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)},U=D;function N(t){return t}function D(t,e){const r=(e=e||{}).delimiter||".",o=e.maxDepth,s=e.transformKey||N,n={};return function t(i,a,c){c=c||1,Object.keys(i).forEach((function(u){const f=i[u],p=e.safe&&Array.isArray(f),l=Object.prototype.toString.call(f),h=P(f),d="[object Object]"===l||"[object Array]"===l,y=a?a+r+s(u):s(u);if(!p&&!h&&d&&Object.keys(f).length&&(!e.maxDepth||c<o))return t(f,y,c+1);n[y]=f}))}(t),n}D.flatten=D,D.unflatten=function t(e,r){const o=(r=r||{}).delimiter||".",s=r.overwrite||!1,n=r.transformKey||N,i={};if(P(e)||"[object Object]"!==Object.prototype.toString.call(e))return e;function a(t){const e=Number(t);return isNaN(e)||-1!==t.indexOf(".")||r.object?t:e}return e=Object.keys(e).reduce((t,s)=>{const n=Object.prototype.toString.call(e[s]);return!("[object Object]"===n||"[object Array]"===n)||function(t){const e=Object.prototype.toString.call(t),r="[object Array]"===e,o="[object Object]"===e;if(!t)return!0;if(r)return!t.length;if(o)return!Object.keys(t).length}(e[s])?(t[s]=e[s],t):function(t,e,r){return Object.keys(r).reduce((function(e,s){return e[t+o+s]=r[s],e}),e)}(s,t,D(e[s],r))},{}),Object.keys(e).forEach((function(c){const u=c.split(o).map(n);let f=a(u.shift()),p=a(u[0]),l=i;for(;void 0!==p;){const t=Object.prototype.toString.call(l[f]),e="[object Object]"===t||"[object Array]"===t;if(!s&&!e&&void 0!==l[f])return;(s&&!e||!s&&null==l[f])&&(l[f]="number"!=typeof p||r.object?{}:[]),l=l[f],u.length>0&&(f=a(u.shift()),p=a(u[0]))}l[f]=t(e[c],r)})),i};const I={FREE:"https://api.microlink.io",PRO:"https://pro.microlink.io"};var L=({VERSION:t,MicrolinkError:e,isUrlHttp:r,stringify:o,got:s,flatten:n})=>{const i=t=>{if("object"!=typeof t)return;const e=n(t);return Object.keys(e).reduce((t,r)=>({...t,[`data.${r}`]:e[r]}),{})},a=async(t,r={})=>{try{const e=await s(t,r),{body:o}=e;return{...o,response:e}}catch(o){const{name:s,message:n,response:i={}}=o,{statusCode:a=500,body:c,headers:u,url:f=t}=i,p=Number((r.retry*r.timeout).toFixed(0)),l="TimeoutError"===s;if(((t,e)=>"TimeoutError"===t.name||"HTTPError"===t.name&&"5"===e.toString()[0]||"invalid-json"===t.type)(o,a)){const t=`The request reached timeout after ${p}ms.`;throw new e({url:f,data:{url:t},status:"fail",code:l?"ETIMEOUTCLIENT":"ETIMEOUT",message:t,more:`https://microlink.io/${l?"etimeoutclient":"etimeout"}`,statusCode:a,headers:u})}const h=c?"string"==typeof c||Buffer.isBuffer(c)?JSON.parse(c):c:{message:n,status:"fail"};throw e({...h,message:h.message,url:f,statusCode:a,headers:u})}},c=(t,{data:e,apiKey:r,endpoint:s,isStream:a=!1,retry:c=3,timeout:u=3e4,responseType:f="json",...p}={})=>{const l=!!r;var h;return[`${s||I[l?"PRO":"FREE"]}?${o({url:t,...i(e),...n((h=p,Object.keys(h).forEach(t=>null==h[t]&&delete h[t]),h))})}`,{retry:c,timeout:u,responseType:f,isStream:a,headers:l?{"x-api-key":r}:{}}]},u=async(t,o={})=>{((t="")=>{if(!r(t)){const r=`The \`url\` as \`${t}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new e({url:t,data:{url:r},status:"fail",code:"EINVALURLCLIENT",message:r,more:"https://microlink.io/docs/api/api-parameters/url"})}})(t);const[s,n]=c(t,o);return a(s,{...o,...n})};return u.MicrolinkError=e,u.getApiUrl=c,u.fetchFromApi=a,u.mapRules=i,u.version=t,u.stream=(t,e)=>u(t,{...e,isStream:!0}),u},$=r(a);const H=o.default||o,{encode:M}=$;return L({MicrolinkError:T("MicrolinkError"),isUrlHttp:t=>{try{return n.test(new s(t).href)}catch(t){return!1}},stringify:M,got:async(t,{responseType:e,...r})=>{try{const e=await H(t,r),o=await e.json(),{headers:s,status:n,statusText:i}=e;return{url:e.url,body:o,headers:s,statusCode:n,statusMessage:i}}catch(t){if(t.response){const{response:e}=t;t.response={...e,statusCode:e.status,body:await e.json()}}throw t}},flatten:U,VERSION:"0.6.0"})})); | ||
//# sourceMappingURL=mql.min.js.map |
@@ -5,3 +5,3 @@ { | ||
"homepage": "https://nicedoc.io/microlinkhq/mql", | ||
"version": "0.5.23", | ||
"version": "0.6.0", | ||
"browser": "src/browser.js", | ||
@@ -8,0 +8,0 @@ "main": "src/node.js", |
@@ -43,3 +43,3 @@ const ENDPOINT = { | ||
const fetchFromApi = async (url, apiUrl, opts = {}) => { | ||
const fetchFromApi = async (apiUrl, opts = {}) => { | ||
try { | ||
@@ -51,14 +51,17 @@ const response = await got(apiUrl, opts) | ||
const { name, message: rawMessage, response = {} } = err | ||
const { statusCode = 500, body: rawBody } = response | ||
const { statusCode = 500, body: rawBody, headers, url: uri = apiUrl } = response | ||
const retryTime = Number((opts.retry * opts.timeout).toFixed(0)) | ||
const isClientError = name === 'TimeoutError' | ||
if (isTimeoutError(err, statusCode)) { | ||
const message = `The \`url\` as \`${url}\` reached timeout after ${opts.retry.maxRetryAfter}ms.` | ||
const message = `The request reached timeout after ${retryTime}ms.` | ||
throw new MicrolinkError({ | ||
url, | ||
url: uri, | ||
data: { url: message }, | ||
status: 'fail', | ||
code: name === 'TimeoutError' ? 'ETIMEOUTCLIENT' : 'ETIMEOUT', | ||
code: isClientError ? 'ETIMEOUTCLIENT' : 'ETIMEOUT', | ||
message, | ||
more: 'https://microlink.io/docs/api/api-parameters/url', | ||
statusCode | ||
more: `https://microlink.io/${isClientError ? 'etimeoutclient' : 'etimeout'}`, | ||
statusCode, | ||
headers | ||
}) | ||
@@ -73,9 +76,8 @@ } | ||
const message = body.data ? body.data[Object.keys(body.data)[0]] : body.message | ||
throw MicrolinkError({ | ||
...body, | ||
message, | ||
url, | ||
statusCode | ||
message: body.message, | ||
url: uri, | ||
statusCode, | ||
headers | ||
}) | ||
@@ -92,3 +94,3 @@ } | ||
isStream = false, | ||
retry = 4, | ||
retry = 3, | ||
timeout = 30000, | ||
@@ -115,3 +117,3 @@ responseType = 'json', | ||
const [apiUrl, fetchOpts] = getApiUrl(url, opts) | ||
return fetchFromApi(url, apiUrl, { ...opts, ...fetchOpts }) | ||
return fetchFromApi(apiUrl, { ...opts, ...fetchOpts }) | ||
} | ||
@@ -118,0 +120,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
174241
1069