@datx/network
Advanced tools
| import { PureModel } from '@datx/core'; | ||
| import { IInterceptor } from './interfaces/IInterceptor'; | ||
| import { IPipeOperator } from './interfaces/IPipeOperator'; | ||
| import { Response } from './Response'; | ||
| import { BodyType } from './enums/BodyType'; | ||
| export declare class BaseRequest<TModel extends PureModel = PureModel, TParams extends object = {}> { | ||
| private _config; | ||
| private _options; | ||
| interceptors: Array<{ | ||
| name: string; | ||
| fn: IInterceptor<TModel>; | ||
| }>; | ||
| constructor(baseUrl: string); | ||
| pipe<TNewModel extends PureModel | Array<PureModel> = TModel, TNewParams extends object = TParams>(...operators: Array<IPipeOperator | undefined>): BaseRequest<TNewModel, TNewParams>; | ||
| private processBody; | ||
| fetch(params?: TParams | null, queryParams?: Record<string, string | Array<string> | object> | null, body?: any, bodyType?: BodyType): Promise<Response<TModel>>; | ||
| clone<TNewModel extends PureModel = TModel, TNewParams extends object = TParams>(BaseRequestConstructor?: typeof BaseRequest): BaseRequest<TNewModel, TNewParams>; | ||
| } |
| export declare const NETWORK_PERSISTED = "networkPersisted"; |
| import { PureCollection } from '@datx/core'; | ||
| import { INetworkCollectionConstructor } from './interfaces/INetworkCollectionConstructor'; | ||
| export declare function decorateCollection(BaseClass: typeof PureCollection): INetworkCollectionConstructor; |
| import { PureModel } from '@datx/core'; | ||
| import { INetworkModelConstructor } from './interfaces/INetworkModelConstructor'; | ||
| export declare function decorateModel(BaseClass: typeof PureModel): INetworkModelConstructor; |
| import { IConfigType } from './interfaces/IConfigType'; | ||
| export declare function getDefaultConfig(): IConfigType; |
| export declare enum BodyType { | ||
| Raw = 0, | ||
| Json = 1, | ||
| Multipart = 2, | ||
| Urlencoded = 3 | ||
| } |
| export declare enum CachingStrategy { | ||
| NetworkOnly = 1, | ||
| NetworkFirst = 2, | ||
| StaleWhileRevalidate = 3, | ||
| CacheOnly = 4, | ||
| CacheFirst = 5, | ||
| StaleAndUpdate = 6 | ||
| } |
| export declare enum HttpMethod { | ||
| Get = "GET", | ||
| Post = "POST", | ||
| Put = "PUT", | ||
| Patch = "Patch", | ||
| Delete = "Delete", | ||
| Options = "Options", | ||
| Head = "Head" | ||
| } |
| export declare enum ParamArrayType { | ||
| MultipleParams = 0, | ||
| CommaSeparated = 1, | ||
| ParamArray = 2 | ||
| } |
| import { INetworkModel } from '../interfaces/INetworkModel'; | ||
| import { IRequestOptions } from '../interfaces/IRequestOptions'; | ||
| export declare function saveModel<TModel extends INetworkModel>(model: TModel, options?: IRequestOptions): Promise<TModel>; | ||
| export declare function removeModel<TModel extends INetworkModel>(model: TModel, options?: IRequestOptions): Promise<void>; |
| import { ParamArrayType } from '../enums/ParamArrayType'; | ||
| import { PureModel, IReferenceDefinition } from '@datx/core'; | ||
| export declare const isBrowser: boolean; | ||
| export declare function deepCopy<T extends object>(inObject: T): T; | ||
| export declare function interpolateParams(url: string, params: Record<string, string>): string; | ||
| export declare function appendQueryParams(url: string, query: Record<string, string | Array<string> | object>, paramArrayType: ParamArrayType, encodeQueryString: boolean): string; | ||
| export declare function getModelClassRefs(type: typeof PureModel | PureModel): Record<string, IReferenceDefinition>; |
| "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@datx/utils"),t=require("@datx/core"),n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)};function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function o(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}var r,i=function(){return i=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};function a(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}exports.ParamArrayType=void 0,(r=exports.ParamArrayType||(exports.ParamArrayType={}))[r.MultipleParams=0]="MultipleParams",r[r.CommaSeparated=1]="CommaSeparated",r[r.ParamArray=2]="ParamArray";var s="undefined"!=typeof window;function c(e){var t,n;if("object"!=typeof e||null===e)return e;var o=Array.isArray(e)?[]:{};for(n in e)t=e[n],o[n]=c(t);return o}var u=/\{\s*([a-zA-Z0-9\-_]+)\s*\}/g;function l(e,t,n){void 0===n&&(n="");var o=[];return Object.keys(t).forEach((function(r){var i="".concat(n).concat(n?"[".concat(r,"]"):r);t[r]instanceof Array?e===exports.ParamArrayType.CommaSeparated?o.push({key:i,value:t[r].join(",")}):e===exports.ParamArrayType.MultipleParams?o.push.apply(o,t[r].map((function(e){return{key:i,value:e}}))):e===exports.ParamArrayType.ParamArray&&o.push.apply(o,t[r].map((function(e){return{key:"".concat(i,"[]"),value:e}}))):"object"==typeof t[r]?o.push.apply(o,l(e,t[r],i)):void 0!==t[r]&&o.push({key:i,value:t[r]})})),o}function p(e,t,n,o){return function(e,t){var n=e;if(t.length){var o="";-1===n.indexOf("?")?o="?":n.endsWith("&")||n.endsWith("?")||(o="&"),n+=o+t.join("&")}return n}(e,l(n,t).map((function(e){var t=e.key,n=e.value;return{key:t,value:o?encodeURIComponent(n):n}})).map((function(e){var t=e.key,n=e.value;return"".concat(t,"=").concat(n)})))}function d(e){if(e instanceof Array)return e;var t=[];return e.forEach((function(e,n){t.push([n,e])})),t}function f(n,o,r){var i=null,a=Boolean(n.data&&Object.keys(n.data).length);if(o&&n.data&&a)i=r||(n.type?o.add(n.data,n.type):o.add(n.data));else if(a){var s=n.type===t.PureModel||Object.isPrototypeOf.call(t.PureModel,n.type||{})?n.type:t.PureModel;return{value:i=r||e.mapItems(n.data,(function(e){return new s(e)}))}}return new t.Bucket.ToOneOrMany(i,o,!0)}var h,y,v=function(){function n(e,t,n,o){var r=this;this.__internal={response:{},views:[]},this.__cache={},this.collection=t,this.__updateInternal(e,o);try{this.__data=f(e,t,n)}catch(e){this.__internal.error=e}if(this.views.forEach((function(e){r.__data.value&&e.add(r.__data.value)})),Object.freeze(this),this.error)throw this}return Object.defineProperty(n.prototype,"headers",{get:function(){return this.__internal.headers},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"requestHeaders",{get:function(){return this.__internal.requestHeaders},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"error",{get:function(){return this.__internal.error},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"status",{get:function(){return this.__internal.status},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"views",{get:function(){return this.__internal.views},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isSuccess",{get:function(){return!this.error},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"data",{get:function(){return this.__data.value},enumerable:!1,configurable:!0}),n.prototype.__updateInternal=function(t,n){var o;this.__internal.response=t,this.__internal.headers=t.headers&&((o=t.headers)instanceof Array?new e.Headers(o):o),this.__internal.requestHeaders=t.requestHeaders,this.__internal.error=t.error,this.__internal.status=t.status,n&&(this.__internal.views=n),this.error||this.status||(this.__internal.error=new Error("Network not available"))},n.prototype.replaceData=function(e){var o=this.data;if(o===e)return this;var r=t.getModelId(o).toString(),i=t.getModelType(o),a=this.views.map((function(e){return e.list.indexOf(o)}));return this.collection&&(this.collection.removeOne(i,r),this.collection.add(e)),t.updateModel(e,t.modelToJSON(o)),t.updateModelId(e,r),this.views.forEach((function(t,n){-1!==a[n]&&(t.list[a[n]]=e)})),new n(this.__internal.response,this.collection,e)},n.prototype.clone=function(){return new n(this.__internal.response,this.collection,this.data||void 0)},Object.defineProperty(n.prototype,"snapshot",{get:function(){return{response:Object.assign({},this.__internal.response,{headers:this.__internal.response.headers&&d(this.__internal.response.headers),collection:void 0})}},enumerable:!1,configurable:!0}),n.prototype.update=function(e,t){var o=e instanceof n?e.__internal.response:e;this.__updateInternal(o,t);var r=f(o,this.collection);return this.__data.__readonlyValue=r.value,this},n}();function g(e,t){return e.data?i(i({},e),{data:t(e.data,e)}):e}function _(e,t,n,o){return void 0===t&&(t=function(e){return e}),void 0===n&&(n=function(e){return e}),void 0===o&&(o=v),function(r,i){var a,s;if(!e)throw new Error("The fetch reference must be defined");var c,u,l=t?t(r):r,p=0,d=l.method.toUpperCase(),f="GET"!==d&&"HEAD"!==d,h="object"!=typeof l.data||l.data instanceof FormData?l.data:JSON.stringify(l.data),y=f?h:void 0,v=Object.assign({},null===(s=null===(a=l.options)||void 0===a?void 0:a.networkConfig)||void 0===s?void 0:s.headers),_=Object.assign({body:y,headers:v,method:l.method});return e(l.url,_).then((function(e){return p=e.status,u=e.headers,e.json()})).catch((function(e){if(204===p)return null;if(0===p)throw new Error("Network not available");throw e})).then((function(e){if(c=e,p>=400)throw{message:"Invalid HTTP status: ".concat(p),status:p};var t=g({data:c,headers:u,requestHeaders:v,status:p,collection:r.collection,type:r.type},n);return new o(t,r.collection,void 0,r.views)})).catch((function(e){var t=g({data:c,error:e,headers:u,requestHeaders:v,status:p,collection:r.collection,type:r.type},n);throw new o(t,r.collection,void 0,r.views)}))}}exports.HttpMethod=void 0,(h=exports.HttpMethod||(exports.HttpMethod={})).Get="GET",h.Post="POST",h.Put="PUT",h.Patch="Patch",h.Delete="Delete",h.Options="Options",h.Head="Head",exports.CachingStrategy=void 0,(y=exports.CachingStrategy||(exports.CachingStrategy={}))[y.NetworkOnly=1]="NetworkOnly",y[y.NetworkFirst=2]="NetworkFirst",y[y.StaleWhileRevalidate=3]="StaleWhileRevalidate",y[y.CacheOnly=4]="CacheOnly",y[y.CacheFirst=5]="CacheFirst",y[y.StaleAndUpdate=6]="StaleAndUpdate";var w,m=[];function b(e){m=m.filter((function(t){return!t.types.includes(e)}))}function O(n,o,r,i){return void 0===r&&(r=!1),o(n).then((function(o){var a=o;return i&&(a=i.update(o,n.views)),r&&function(n,o){if(o&&o.isSuccess&&(o.data||null===o.data)){var r=e.mapItems(o.data||[],t.getModelType);(m=m.filter((function(e){return e.url!==n}))).unshift({response:o.snapshot,collection:o.collection,time:Date.now(),types:[].concat(r),url:n})}}(n.url,a),a}),(function(e){throw e}))}function x(e,t,n){var o,r;return new v({error:new Error(e),collection:n,requestHeaders:null===(r=null===(o=t.options)||void 0===o?void 0:o.networkConfig)||void 0===r?void 0:r.headers},n)}function k(e,t){return void 0===t&&(t=1/0),function(n,o){var r,i,a,s,c;if(!o)throw new Error("Cache interceptor can't be the last interceptor");var u=n.method.toUpperCase()===exports.HttpMethod.Get,l=(null===(i=null===(r=n.options)||void 0===r?void 0:r.cacheOptions)||void 0===i?void 0:i.skipCache)||!u?exports.CachingStrategy.NetworkOnly:(null===(s=null===(a=n.options)||void 0===a?void 0:a.cacheOptions)||void 0===s?void 0:s.cachingStrategy)||e;if(l===exports.CachingStrategy.NetworkOnly)return O(n,o);var p=function(e,t){var n=Date.now()-1e3*t,o=m.find((function(t){return t.url===e&&t.time>n}));if(o){var r=o.response;return{response:new v(r.response,o.collection,r.options),time:o.time,types:o.types,url:o.url}}}(n.url,t);if(l===exports.CachingStrategy.NetworkFirst)return O(n,o,!0).catch((function(e){if(p)return p.response;throw e}));if(l===exports.CachingStrategy.StaleWhileRevalidate){var d=O(n,o,!0);return p?(d.catch((function(){})),Promise.resolve(p.response)):d}if(l===exports.CachingStrategy.CacheOnly)return p?Promise.resolve(p.response):Promise.reject(x("No cache for this request",n,null==n?void 0:n.collection));if(l===exports.CachingStrategy.CacheFirst)return p?Promise.resolve(p.response):O(n,o,!0);if(l===exports.CachingStrategy.StaleAndUpdate){var f=null===(c=null==p?void 0:p.response)||void 0===c?void 0:c.clone();return d=O(n,o,!0,f),f?(d.catch((function(){})),Promise.resolve(f)):d}return Promise.reject(x("Invalid caching strategy",n,null==n?void 0:n.collection))}}function P(e,n){return void 0===n&&(n=t.PureModel),function(t){t._options.url=e,t._config.type=n}}function T(e,t){return void 0===t&&(t=e.name),function(n){var o=n.interceptors.find((function(e){return e.name===t}));o?o.fn=e:n.interceptors.push({name:t,fn:e})}}function M(e,t){return void 0===t&&(t=1/0),T(k(e,t),"cache")}function C(e){return function(t){t._options.method=e}}function S(e,t){return function(n){t||0===t?n._options.bodyType=t:e instanceof FormData?n._options.bodyType=w.Multipart:n._options.bodyType="object"==typeof e?w.Json:w.Raw,n._options.body=e}}function j(e,t){return function(n){"string"==typeof e?n._options.query[e]=t:Object.assign(n._options.query,e)}}function A(e,t){return function(n){"string"==typeof e?n._options.headers[e]=t||"":Object.assign(n._options.headers,e)}}function E(e){return function(t){var n,o,r,i,a;(null==e?void 0:e.query)&&j(null==e?void 0:e.query)(t),(null===(n=null==e?void 0:e.networkConfig)||void 0===n?void 0:n.headers)&&A(null===(o=null==e?void 0:e.networkConfig)||void 0===o?void 0:o.headers)(t),(null===(r=null==e?void 0:e.cacheOptions)||void 0===r?void 0:r.cachingStrategy)&&M(null===(i=null==e?void 0:e.cacheOptions)||void 0===i?void 0:i.cachingStrategy,null===(a=null==e?void 0:e.cacheOptions)||void 0===a?void 0:a.maxAge)(t)}}!function(e){e[e.Raw=0]="Raw",e[e.Json=1]="Json",e[e.Multipart=2]="Multipart",e[e.Urlencoded=3]="Urlencoded"}(w||(w={}));var q=function(){function n(n){var o,r;this._config={baseUrl:"/",encodeQueryString:!0,paramArrayType:exports.ParamArrayType.ParamArray,fetchReference:s?null===(r=null===(o=window.fetch)||void 0===o?void 0:o.bind)||void 0===r?void 0:r.call(o,window):void 0,fetchInterceptor:_,serialize:function(n){return i(i({},n),{data:e.mapItems(n.data,(function(e){return e instanceof t.PureModel?t.modelToJSON(e):e}))||void 0})},Response:v},this._options={method:exports.HttpMethod.Get,headers:{},query:{},params:{},bodyType:w.Json},this.interceptors=[{fn:_(this._config.fetchReference,this._config.serialize,this._config.parse),name:"fetch"},{fn:k(s?exports.CachingStrategy.CacheFirst:exports.CachingStrategy.NetworkOnly),name:"cache"}],this._config.baseUrl=n}return n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.clone();return e.filter(Boolean).forEach((function(e){return e(n)})),n},n.prototype.processBody=function(){if(this._options.body)return this._options.bodyType===w.Json?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/json",this._options.body):this._options.bodyType===w.Urlencoded?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/x-www-form-urlencoded","string"==typeof this._options.body?this._options.body:p("",this._options.body,this._config.paramArrayType,this._config.encodeQueryString).slice(1)):this._options.bodyType===w.Multipart?(this._options.headers["content-type"]=this._options.headers["content-type"]||"multipart/form-data",this._options.body instanceof FormData?this._options.body:new FormData(this._options.body)):this._options.body},n.prototype.fetch=function(e,t,n,o){var r=void 0===n?this:this.pipe(S(n,o));if(!r._options.url)throw new Error("URL should be defined");var i=Object.assign({},r._options.params,e||{}),a=function(e,t){for(var n=e,o=u.exec(n),r=0;o;){var i=t[o[1]];void 0===i&&(i=o[0],r=u.lastIndex),n=n.replace(o[0],i),u.lastIndex=r,o=u.exec(n)}return n}("".concat(r._config.baseUrl).concat(r._options.url),i),s={url:p(a,Object.assign({},r._options.query,t),r._config.paramArrayType,r._config.encodeQueryString),method:r._options.method,data:r.processBody(),collection:r._config.collection,params:e,options:{networkConfig:{headers:r._options.headers}},views:r._config.views,type:r._config.type},c=r.interceptors.reduce((function(e,t){return function(n){return t.fn(n,e)}}),void 0);if(!c)throw new Error("Something went wrong");return c(s)},n.prototype.clone=function(e){void 0===e&&(e=this.constructor);var t=new e(this._config.baseUrl);return t.interceptors=c(this.interceptors),t._config=c(this._config),t._options=c(this._options),t._config.collection=this._config.collection,t._config.fetchInterceptor=this._config.fetchInterceptor,t._config.fetchReference=this._config.fetchReference,t._config.Response=this._config.Response,t._config.type=this._config.type,t},n}();function R(e,t){return e.pipe(E(t))}var I="networkPersisted",H=[I];exports.BaseRequest=q,exports.Response=v,exports.addInterceptor=function(e,t){return void 0===t&&(t=e.name),function(n){n.interceptors=n.interceptors.filter((function(e){return e.name!==t})),n.interceptors.push({name:t,fn:e})}},exports.body=S,exports.cache=M,exports.clearAllCache=function(){m.length=0},exports.clearCacheByType=b,exports.collection=function(e){return function(t){t._config.collection=e}},exports.encodeQueryString=function(e){return function(t){t._config.encodeQueryString=e}},exports.fetchReference=function(e){return function(t){var n=t._config;n.fetchReference=e,T(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}},exports.header=A,exports.method=C,exports.paramArrayType=function(e){return function(t){t._config.paramArrayType=e}},exports.params=function(e,t){return function(n){"string"==typeof e?n._options.params[e]=t:Object.assign(n._options.params,e)}},exports.parser=function(e){return function(t){var n=t._config;n.parse=e,T(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}},exports.query=j,exports.requestOptions=E,exports.serializer=function(e){return function(t){var n=t._config;n.serialize=e,T(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}},exports.setUrl=P,exports.upsertInterceptor=T,exports.withNetwork=function(n){if(t.isModel(n))return function(n){function r(t,o){void 0===t&&(t={});var r=n.call(this,t,o)||this,i=(null==t?void 0:t[e.META_FIELD])||{};return H.forEach((function(t){t in i&&e.setMeta(r,t,i[t])})),r}return o(r,n),r.prototype.save=function(n){return function(n,o){var r,i,a,s,c,u=n.constructor;if(!u.network)throw new Error("The network property needs to be defined on the model");var l,p,d=e.getMeta(n,I,!1);if(!(l=u.network instanceof q?d?u.network.pipe(C(exports.HttpMethod.Put),P("".concat(u.network._options.url,"/{id}"),u)):u.network.pipe(C(exports.HttpMethod.Post)):d?u.network.update:u.network.create))throw new Error("The base request has not been defined");return l.pipe((null==o?void 0:o.query)&&j(null==o?void 0:o.query),(null===(r=null==o?void 0:o.networkConfig)||void 0===r?void 0:r.headers)&&A(null===(i=null==o?void 0:o.networkConfig)||void 0===i?void 0:i.headers),(null===(a=null==o?void 0:o.cacheOptions)||void 0===a?void 0:a.cachingStrategy)&&M(null===(s=null==o?void 0:o.cacheOptions)||void 0===s?void 0:s.cachingStrategy,null===(c=null==o?void 0:o.cacheOptions)||void 0===c?void 0:c.maxAge),S(n)).fetch({id:t.getModelId(n)}).then((p=n,function(n){if(n.error)throw n.error;if(204===n.status)return e.setMeta(p,I,!0),p;e.setMeta(p,I,!0);var o=n.replaceData(p).data||p;return t.commitModel(o),o}))}(this,n)},r.prototype.destroy=function(n){return function(n,o){var r,i,a,s,c,u=n.constructor;if(!u.network)throw new Error("The network property needs to be defined on the model");var l,p=e.getMeta(n,I,!1);if(!(l=u.network instanceof q?!!p&&u.network.pipe(C(exports.HttpMethod.Delete),P("".concat(u.network._options.url,"/{id}"),u)):!!p&&u.network.destroy)&&!1!==l)throw new Error("The base request has not been defined");return l&&l.pipe((null==o?void 0:o.query)&&j(null==o?void 0:o.query),(null===(r=null==o?void 0:o.networkConfig)||void 0===r?void 0:r.headers)&&A(null===(i=null==o?void 0:o.networkConfig)||void 0===i?void 0:i.headers),(null===(a=null==o?void 0:o.cacheOptions)||void 0===a?void 0:a.cachingStrategy)&&M(null===(s=null==o?void 0:o.cacheOptions)||void 0===s?void 0:s.cachingStrategy,null===(c=null==o?void 0:o.cacheOptions)||void 0===c?void 0:c.maxAge)).fetch({id:t.getModelId(n)}).then((function(){var e=t.getModelCollection(n);e&&e.removeOne(n)})),Promise.resolve()}(this,n)},r}(n);if(t.isCollection(n))return function(e){function n(t){void 0===t&&(t=[]);var n,o,r=e.call(this,t)||this;return t instanceof Array||!(null==t?void 0:t.cache)||(n=t.cache,o=r,m.push.apply(m,a(a([],m,!1),n.map((function(e){return Object.assign({collection:o},e)})),!1))),r}return o(n,e),n.prototype.getConstructor=function(e){var n=this.constructor,o=t.getModelType(e);return n.types.find((function(e){return t.getModelType(e)===o}))||n.defaultModel},n.prototype.getOne=function(e,t,n){var o=this.getConstructor(e);if(!o||!o.network)throw new Error("The network configuration is wrong for the given model");if(o.network instanceof q)return o.network.pipe(E(n),P("".concat(o.network._options.url,"/{id}"),o)).fetch({id:t});if(!o.network.getOne)throw new Error("The getOne network request was not defined on the given model");return R(o.network.getOne,n).fetch({id:t})},n.prototype.getMany=function(e,t){var n=this.getConstructor(e);if(!n||!n.network)throw new Error("The network configuration is wrong for the given model");if(n.network instanceof q)return R(n.network,t).fetch();if(!n.network.getMany)throw new Error("The getMany network request was not defined on the given model");return R(n.network.getMany,t).fetch()},n.prototype.removeOne=function(n,o,r){var i=this,a=t.getModelType(n),s="object"!=typeof o&&void 0!==o&&"boolean"!=typeof o?o:null,c=null!==s?r:o,u=s?this.findOne(a,s):a;if(!u)throw new Error("The model was not found");return!1===c||void 0===c?Promise.resolve(e.prototype.removeOne.call(this,u)):(b(t.getModelType(n)),u.destroy("object"==typeof c?c:{}).then((function(){e.prototype.removeOne.call(i,u)})))},n.prototype.toJSON=function(){return Object.assign({},e.prototype.toJSON.call(this),{cache:(t=this,m.filter((function(e){return e.collection===t})).map((function(e){return Object.assign({},e,{collection:void 0})})))});var t},n}(n);throw new Error("The instance needs to be a model, collection or a view")}; | ||
| //# sourceMappingURL=index.cjs.js.map |
Sorry, the diff of this file is too big to display
+19
| export { BaseRequest } from './BaseRequest'; | ||
| export { Response } from './Response'; | ||
| export { addInterceptor, cache, method, setUrl, body, query, header, params, fetchReference, encodeQueryString, paramArrayType, serializer, parser, collection, requestOptions, upsertInterceptor, } from './operators'; | ||
| export { IResponseHeaders } from '@datx/utils'; | ||
| export { clearAllCache, clearCacheByType } from './interceptors/cache'; | ||
| export { CachingStrategy } from './enums/CachingStrategy'; | ||
| export { HttpMethod } from './enums/HttpMethod'; | ||
| export { ParamArrayType } from './enums/ParamArrayType'; | ||
| export { IFetchOptions } from './interfaces/IFetchOptions'; | ||
| export { IHeaders } from './interfaces/IHeaders'; | ||
| export { IInterceptor } from './interfaces/IInterceptor'; | ||
| export { INetworkHandler } from './interfaces/INetworkHandler'; | ||
| export { IPipeOperator } from './interfaces/IPipeOperator'; | ||
| export { IResponseObject } from './interfaces/IResponseObject'; | ||
| export { withNetwork } from './withNetwork'; | ||
| export { INetworkCollection } from './interfaces/INetworkCollection'; | ||
| export { INetworkCollectionConstructor } from './interfaces/INetworkCollectionConstructor'; | ||
| export { INetworkModel } from './interfaces/INetworkModel'; | ||
| export { INetworkModelConstructor } from './interfaces/INetworkModelConstructor'; |
| import{Headers as e,mapItems as t,getMeta as n,setMeta as o,META_FIELD as r}from"@datx/utils";import{getModelId as i,getModelType as a,updateModel as c,modelToJSON as s,updateModelId as u,PureModel as l,Bucket as f,getModelCollection as p,commitModel as d,isModel as h,isCollection as v}from"@datx/core";var y=function(e,t){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},y(e,t)};function _(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}y(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var w,g=function(){return g=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},g.apply(this,arguments)};function m(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}!function(e){e[e.MultipleParams=0]="MultipleParams",e[e.CommaSeparated=1]="CommaSeparated",e[e.ParamArray=2]="ParamArray"}(w||(w={}));var b="undefined"!=typeof window;function O(e){var t,n;if("object"!=typeof e||null===e)return e;var o=Array.isArray(e)?[]:{};for(n in e)t=e[n],o[n]=O(t);return o}var k=/\{\s*([a-zA-Z0-9\-_]+)\s*\}/g;function j(e,t,n){void 0===n&&(n="");var o=[];return Object.keys(t).forEach((function(r){var i="".concat(n).concat(n?"[".concat(r,"]"):r);t[r]instanceof Array?e===w.CommaSeparated?o.push({key:i,value:t[r].join(",")}):e===w.MultipleParams?o.push.apply(o,t[r].map((function(e){return{key:i,value:e}}))):e===w.ParamArray&&o.push.apply(o,t[r].map((function(e){return{key:"".concat(i,"[]"),value:e}}))):"object"==typeof t[r]?o.push.apply(o,j(e,t[r],i)):void 0!==t[r]&&o.push({key:i,value:t[r]})})),o}function P(e,t,n,o){return function(e,t){var n=e;if(t.length){var o="";-1===n.indexOf("?")?o="?":n.endsWith("&")||n.endsWith("?")||(o="&"),n+=o+t.join("&")}return n}(e,j(n,t).map((function(e){var t=e.key,n=e.value;return{key:t,value:o?encodeURIComponent(n):n}})).map((function(e){var t=e.key,n=e.value;return"".concat(t,"=").concat(n)})))}function T(e){if(e instanceof Array)return e;var t=[];return e.forEach((function(e,n){t.push([n,e])})),t}function S(e,n,o){var r=null,i=Boolean(e.data&&Object.keys(e.data).length);if(n&&e.data&&i)r=o||(e.type?n.add(e.data,e.type):n.add(e.data));else if(i){var a=e.type===l||Object.isPrototypeOf.call(l,e.type||{})?e.type:l;return{value:r=o||t(e.data,(function(e){return new a(e)}))}}return new f.ToOneOrMany(r,n,!0)}var C,E,A=function(){function t(e,t,n,o){var r=this;this.__internal={response:{},views:[]},this.__cache={},this.collection=t,this.__updateInternal(e,o);try{this.__data=S(e,t,n)}catch(e){this.__internal.error=e}if(this.views.forEach((function(e){r.__data.value&&e.add(r.__data.value)})),Object.freeze(this),this.error)throw this}return Object.defineProperty(t.prototype,"headers",{get:function(){return this.__internal.headers},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"requestHeaders",{get:function(){return this.__internal.requestHeaders},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"error",{get:function(){return this.__internal.error},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"status",{get:function(){return this.__internal.status},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"views",{get:function(){return this.__internal.views},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isSuccess",{get:function(){return!this.error},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"data",{get:function(){return this.__data.value},enumerable:!1,configurable:!0}),t.prototype.__updateInternal=function(t,n){var o;this.__internal.response=t,this.__internal.headers=t.headers&&((o=t.headers)instanceof Array?new e(o):o),this.__internal.requestHeaders=t.requestHeaders,this.__internal.error=t.error,this.__internal.status=t.status,n&&(this.__internal.views=n),this.error||this.status||(this.__internal.error=new Error("Network not available"))},t.prototype.replaceData=function(e){var n=this.data;if(n===e)return this;var o=i(n).toString(),r=a(n),l=this.views.map((function(e){return e.list.indexOf(n)}));return this.collection&&(this.collection.removeOne(r,o),this.collection.add(e)),c(e,s(n)),u(e,o),this.views.forEach((function(t,n){-1!==l[n]&&(t.list[l[n]]=e)})),new t(this.__internal.response,this.collection,e)},t.prototype.clone=function(){return new t(this.__internal.response,this.collection,this.data||void 0)},Object.defineProperty(t.prototype,"snapshot",{get:function(){return{response:Object.assign({},this.__internal.response,{headers:this.__internal.response.headers&&T(this.__internal.response.headers),collection:void 0})}},enumerable:!1,configurable:!0}),t.prototype.update=function(e,n){var o=e instanceof t?e.__internal.response:e;this.__updateInternal(o,n);var r=S(o,this.collection);return this.__data.__readonlyValue=r.value,this},t}();function q(e,t){return e.data?g(g({},e),{data:t(e.data,e)}):e}function R(e,t,n,o){return void 0===t&&(t=function(e){return e}),void 0===n&&(n=function(e){return e}),void 0===o&&(o=A),function(r,i){var a,c;if(!e)throw new Error("The fetch reference must be defined");var s,u,l=t?t(r):r,f=0,p=l.method.toUpperCase(),d="GET"!==p&&"HEAD"!==p,h="object"!=typeof l.data||l.data instanceof FormData?l.data:JSON.stringify(l.data),v=d?h:void 0,y=Object.assign({},null===(c=null===(a=l.options)||void 0===a?void 0:a.networkConfig)||void 0===c?void 0:c.headers),_=Object.assign({body:v,headers:y,method:l.method});return e(l.url,_).then((function(e){return f=e.status,u=e.headers,e.json()})).catch((function(e){if(204===f)return null;if(0===f)throw new Error("Network not available");throw e})).then((function(e){if(s=e,f>=400)throw{message:"Invalid HTTP status: ".concat(f),status:f};var t=q({data:s,headers:u,requestHeaders:y,status:f,collection:r.collection,type:r.type},n);return new o(t,r.collection,void 0,r.views)})).catch((function(e){var t=q({data:s,error:e,headers:u,requestHeaders:y,status:f,collection:r.collection,type:r.type},n);throw new o(t,r.collection,void 0,r.views)}))}}!function(e){e.Get="GET",e.Post="POST",e.Put="PUT",e.Patch="Patch",e.Delete="Delete",e.Options="Options",e.Head="Head"}(C||(C={})),function(e){e[e.NetworkOnly=1]="NetworkOnly",e[e.NetworkFirst=2]="NetworkFirst",e[e.StaleWhileRevalidate=3]="StaleWhileRevalidate",e[e.CacheOnly=4]="CacheOnly",e[e.CacheFirst=5]="CacheFirst",e[e.StaleAndUpdate=6]="StaleAndUpdate"}(E||(E={}));var U,x=[];function I(){x.length=0}function N(e){x=x.filter((function(t){return!t.types.includes(e)}))}function M(e){return x.filter((function(t){return t.collection===e})).map((function(e){return Object.assign({},e,{collection:void 0})}))}function D(e,n,o,r){return void 0===o&&(o=!1),n(e).then((function(n){var i=n;return r&&(i=r.update(n,e.views)),o&&function(e,n){if(n&&n.isSuccess&&(n.data||null===n.data)){var o=t(n.data||[],a);(x=x.filter((function(t){return t.url!==e}))).unshift({response:n.snapshot,collection:n.collection,time:Date.now(),types:[].concat(o),url:e})}}(e.url,i),i}),(function(e){throw e}))}function F(e,t,n){var o,r;return new A({error:new Error(e),collection:n,requestHeaders:null===(r=null===(o=t.options)||void 0===o?void 0:o.networkConfig)||void 0===r?void 0:r.headers},n)}function H(e,t){return void 0===t&&(t=1/0),function(n,o){var r,i,a,c,s;if(!o)throw new Error("Cache interceptor can't be the last interceptor");var u=n.method.toUpperCase()===C.Get,l=(null===(i=null===(r=n.options)||void 0===r?void 0:r.cacheOptions)||void 0===i?void 0:i.skipCache)||!u?E.NetworkOnly:(null===(c=null===(a=n.options)||void 0===a?void 0:a.cacheOptions)||void 0===c?void 0:c.cachingStrategy)||e;if(l===E.NetworkOnly)return D(n,o);var f=function(e,t){var n=Date.now()-1e3*t,o=x.find((function(t){return t.url===e&&t.time>n}));if(o){var r=o.response;return{response:new A(r.response,o.collection,r.options),time:o.time,types:o.types,url:o.url}}}(n.url,t);if(l===E.NetworkFirst)return D(n,o,!0).catch((function(e){if(f)return f.response;throw e}));if(l===E.StaleWhileRevalidate){var p=D(n,o,!0);return f?(p.catch((function(){})),Promise.resolve(f.response)):p}if(l===E.CacheOnly)return f?Promise.resolve(f.response):Promise.reject(F("No cache for this request",n,null==n?void 0:n.collection));if(l===E.CacheFirst)return f?Promise.resolve(f.response):D(n,o,!0);if(l===E.StaleAndUpdate){var d=null===(s=null==f?void 0:f.response)||void 0===s?void 0:s.clone();return p=D(n,o,!0,d),d?(p.catch((function(){})),Promise.resolve(d)):p}return Promise.reject(F("Invalid caching strategy",n,null==n?void 0:n.collection))}}function z(e,t){return void 0===t&&(t=l),function(n){n._options.url=e,n._config.type=t}}function J(e,t){return void 0===t&&(t=e.name),function(n){n.interceptors=n.interceptors.filter((function(e){return e.name!==t})),n.interceptors.push({name:t,fn:e})}}function G(e,t){return void 0===t&&(t=e.name),function(n){var o=n.interceptors.find((function(e){return e.name===t}));o?o.fn=e:n.interceptors.push({name:t,fn:e})}}function W(e,t){return void 0===t&&(t=1/0),G(H(e,t),"cache")}function B(e){return function(t){t._options.method=e}}function Q(e,t){return function(n){t||0===t?n._options.bodyType=t:e instanceof FormData?n._options.bodyType=U.Multipart:n._options.bodyType="object"==typeof e?U.Json:U.Raw,n._options.body=e}}function L(e,t){return function(n){"string"==typeof e?n._options.query[e]=t:Object.assign(n._options.query,e)}}function V(e,t){return function(n){"string"==typeof e?n._options.headers[e]=t||"":Object.assign(n._options.headers,e)}}function Z(e,t){return function(n){"string"==typeof e?n._options.params[e]=t:Object.assign(n._options.params,e)}}function K(e){return function(t){t._config.encodeQueryString=e}}function X(e){return function(t){t._config.paramArrayType=e}}function Y(e){return function(t){var n=t._config;n.fetchReference=e,G(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}}function $(e){return function(t){var n=t._config;n.serialize=e,G(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}}function ee(e){return function(t){var n=t._config;n.parse=e,G(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}}function te(e){return function(t){t._config.collection=e}}function ne(e){return function(t){var n,o,r,i,a;(null==e?void 0:e.query)&&L(null==e?void 0:e.query)(t),(null===(n=null==e?void 0:e.networkConfig)||void 0===n?void 0:n.headers)&&V(null===(o=null==e?void 0:e.networkConfig)||void 0===o?void 0:o.headers)(t),(null===(r=null==e?void 0:e.cacheOptions)||void 0===r?void 0:r.cachingStrategy)&&W(null===(i=null==e?void 0:e.cacheOptions)||void 0===i?void 0:i.cachingStrategy,null===(a=null==e?void 0:e.cacheOptions)||void 0===a?void 0:a.maxAge)(t)}}!function(e){e[e.Raw=0]="Raw",e[e.Json=1]="Json",e[e.Multipart=2]="Multipart",e[e.Urlencoded=3]="Urlencoded"}(U||(U={}));var oe=function(){function e(e){var n,o;this._config={baseUrl:"/",encodeQueryString:!0,paramArrayType:w.ParamArray,fetchReference:b?null===(o=null===(n=window.fetch)||void 0===n?void 0:n.bind)||void 0===o?void 0:o.call(n,window):void 0,fetchInterceptor:R,serialize:function(e){return g(g({},e),{data:t(e.data,(function(e){return e instanceof l?s(e):e}))||void 0})},Response:A},this._options={method:C.Get,headers:{},query:{},params:{},bodyType:U.Json},this.interceptors=[{fn:R(this._config.fetchReference,this._config.serialize,this._config.parse),name:"fetch"},{fn:H(b?E.CacheFirst:E.NetworkOnly),name:"cache"}],this._config.baseUrl=e}return e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.clone();return e.filter(Boolean).forEach((function(e){return e(n)})),n},e.prototype.processBody=function(){if(this._options.body)return this._options.bodyType===U.Json?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/json",this._options.body):this._options.bodyType===U.Urlencoded?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/x-www-form-urlencoded","string"==typeof this._options.body?this._options.body:P("",this._options.body,this._config.paramArrayType,this._config.encodeQueryString).slice(1)):this._options.bodyType===U.Multipart?(this._options.headers["content-type"]=this._options.headers["content-type"]||"multipart/form-data",this._options.body instanceof FormData?this._options.body:new FormData(this._options.body)):this._options.body},e.prototype.fetch=function(e,t,n,o){var r=void 0===n?this:this.pipe(Q(n,o));if(!r._options.url)throw new Error("URL should be defined");var i=Object.assign({},r._options.params,e||{}),a=function(e,t){for(var n=e,o=k.exec(n),r=0;o;){var i=t[o[1]];void 0===i&&(i=o[0],r=k.lastIndex),n=n.replace(o[0],i),k.lastIndex=r,o=k.exec(n)}return n}("".concat(r._config.baseUrl).concat(r._options.url),i),c={url:P(a,Object.assign({},r._options.query,t),r._config.paramArrayType,r._config.encodeQueryString),method:r._options.method,data:r.processBody(),collection:r._config.collection,params:e,options:{networkConfig:{headers:r._options.headers}},views:r._config.views,type:r._config.type},s=r.interceptors.reduce((function(e,t){return function(n){return t.fn(n,e)}}),void 0);if(!s)throw new Error("Something went wrong");return s(c)},e.prototype.clone=function(e){void 0===e&&(e=this.constructor);var t=new e(this._config.baseUrl);return t.interceptors=O(this.interceptors),t._config=O(this._config),t._options=O(this._options),t._config.collection=this._config.collection,t._config.fetchInterceptor=this._config.fetchInterceptor,t._config.fetchReference=this._config.fetchReference,t._config.Response=this._config.Response,t._config.type=this._config.type,t},e}();function re(e,t){return e.pipe(ne(t))}var ie="networkPersisted",ae=[ie];function ce(e){if(h(e))return t=function(e){function t(t,n){void 0===t&&(t={});var i=e.call(this,t,n)||this,a=(null==t?void 0:t[r])||{};return ae.forEach((function(e){e in a&&o(i,e,a[e])})),i}return _(t,e),t.prototype.save=function(e){return function(e,t){var r,a,c,s,u,l=e.constructor;if(!l.network)throw new Error("The network property needs to be defined on the model");var f,p,h=n(e,ie,!1);if(!(f=l.network instanceof oe?h?l.network.pipe(B(C.Put),z("".concat(l.network._options.url,"/{id}"),l)):l.network.pipe(B(C.Post)):h?l.network.update:l.network.create))throw new Error("The base request has not been defined");return f.pipe((null==t?void 0:t.query)&&L(null==t?void 0:t.query),(null===(r=null==t?void 0:t.networkConfig)||void 0===r?void 0:r.headers)&&V(null===(a=null==t?void 0:t.networkConfig)||void 0===a?void 0:a.headers),(null===(c=null==t?void 0:t.cacheOptions)||void 0===c?void 0:c.cachingStrategy)&&W(null===(s=null==t?void 0:t.cacheOptions)||void 0===s?void 0:s.cachingStrategy,null===(u=null==t?void 0:t.cacheOptions)||void 0===u?void 0:u.maxAge),Q(e)).fetch({id:i(e)}).then((p=e,function(e){if(e.error)throw e.error;if(204===e.status)return o(p,ie,!0),p;o(p,ie,!0);var t=e.replaceData(p).data||p;return d(t),t}))}(this,e)},t.prototype.destroy=function(e){return function(e,t){var o,r,a,c,s,u=e.constructor;if(!u.network)throw new Error("The network property needs to be defined on the model");var l,f=n(e,ie,!1);if(!(l=u.network instanceof oe?!!f&&u.network.pipe(B(C.Delete),z("".concat(u.network._options.url,"/{id}"),u)):!!f&&u.network.destroy)&&!1!==l)throw new Error("The base request has not been defined");return l&&l.pipe((null==t?void 0:t.query)&&L(null==t?void 0:t.query),(null===(o=null==t?void 0:t.networkConfig)||void 0===o?void 0:o.headers)&&V(null===(r=null==t?void 0:t.networkConfig)||void 0===r?void 0:r.headers),(null===(a=null==t?void 0:t.cacheOptions)||void 0===a?void 0:a.cachingStrategy)&&W(null===(c=null==t?void 0:t.cacheOptions)||void 0===c?void 0:c.cachingStrategy,null===(s=null==t?void 0:t.cacheOptions)||void 0===s?void 0:s.maxAge)).fetch({id:i(e)}).then((function(){var t=p(e);t&&t.removeOne(e)})),Promise.resolve()}(this,e)},t}(e),t;var t,c;if(v(e))return c=function(e){function t(t){void 0===t&&(t=[]);var n=e.call(this,t)||this;return t instanceof Array||!(null==t?void 0:t.cache)||function(e,t){x.push.apply(x,m(m([],x,!1),e.map((function(e){return Object.assign({collection:t},e)})),!1))}(t.cache,n),n}return _(t,e),t.prototype.getConstructor=function(e){var t=this.constructor,n=a(e);return t.types.find((function(e){return a(e)===n}))||t.defaultModel},t.prototype.getOne=function(e,t,n){var o=this.getConstructor(e);if(!o||!o.network)throw new Error("The network configuration is wrong for the given model");if(o.network instanceof oe)return o.network.pipe(ne(n),z("".concat(o.network._options.url,"/{id}"),o)).fetch({id:t});if(!o.network.getOne)throw new Error("The getOne network request was not defined on the given model");return re(o.network.getOne,n).fetch({id:t})},t.prototype.getMany=function(e,t){var n=this.getConstructor(e);if(!n||!n.network)throw new Error("The network configuration is wrong for the given model");if(n.network instanceof oe)return re(n.network,t).fetch();if(!n.network.getMany)throw new Error("The getMany network request was not defined on the given model");return re(n.network.getMany,t).fetch()},t.prototype.removeOne=function(t,n,o){var r=this,i=a(t),c="object"!=typeof n&&void 0!==n&&"boolean"!=typeof n?n:null,s=null!==c?o:n,u=c?this.findOne(i,c):i;if(!u)throw new Error("The model was not found");return!1===s||void 0===s?Promise.resolve(e.prototype.removeOne.call(this,u)):(N(a(t)),u.destroy("object"==typeof s?s:{}).then((function(){e.prototype.removeOne.call(r,u)})))},t.prototype.toJSON=function(){return Object.assign({},e.prototype.toJSON.call(this),{cache:M(this)})},t}(e),c;throw new Error("The instance needs to be a model, collection or a view")}export{oe as BaseRequest,E as CachingStrategy,C as HttpMethod,w as ParamArrayType,A as Response,J as addInterceptor,Q as body,W as cache,I as clearAllCache,N as clearCacheByType,te as collection,K as encodeQueryString,Y as fetchReference,V as header,B as method,X as paramArrayType,Z as params,ee as parser,L as query,ne as requestOptions,$ as serializer,z as setUrl,G as upsertInterceptor,ce as withNetwork}; | ||
| //# sourceMappingURL=index.esm.js.map |
Sorry, the diff of this file is too big to display
| import { IType, PureModel, PureCollection } from '@datx/core'; | ||
| import { Response } from '../Response'; | ||
| import { IResponseSnapshot } from '../interfaces/IResponseSnapshot'; | ||
| import { CachingStrategy } from '../enums/CachingStrategy'; | ||
| import { IFetchOptions } from '../interfaces/IFetchOptions'; | ||
| import { INetworkHandler } from '../interfaces/INetworkHandler'; | ||
| export interface ICache { | ||
| response: Response<PureModel>; | ||
| time: number; | ||
| types: Array<IType>; | ||
| url: string; | ||
| } | ||
| export interface ICacheInternal { | ||
| response: IResponseSnapshot; | ||
| collection?: PureCollection; | ||
| time: number; | ||
| types: Array<IType>; | ||
| url: string; | ||
| } | ||
| export declare function saveCache(url: string, response: Response<PureModel>): void; | ||
| export declare function getCache(url: string, maxAge: number): ICache | undefined; | ||
| export declare function clearAllCache(): void; | ||
| export declare function clearCacheByType(type: IType): void; | ||
| export declare function getCacheByCollection(collection?: PureCollection): Array<Omit<ICacheInternal, 'collection'>>; | ||
| export declare function saveCacheForCollection(cacheItems: Array<Omit<ICacheInternal, 'collection'>>, collection?: PureCollection): void; | ||
| export declare function cacheInterceptor<T extends PureModel>(cache: CachingStrategy, maxCacheAge?: number): (request: IFetchOptions, next?: INetworkHandler) => Promise<Response<T>>; |
| import { PureModel } from '@datx/core'; | ||
| import { IFetchOptions } from '../interfaces/IFetchOptions'; | ||
| import { INetworkHandler } from '../interfaces/INetworkHandler'; | ||
| import { IResponseObject } from '../interfaces/IResponseObject'; | ||
| import { Response as ResponseClass } from '../Response'; | ||
| export declare function fetchInterceptor<T extends PureModel>(fetchReference?: typeof fetch, serialize?: (options: IFetchOptions) => IFetchOptions, parse?: (data: object, options: IResponseObject) => object, Response?: typeof ResponseClass): (request: IFetchOptions, _next?: INetworkHandler) => Promise<ResponseClass<T>>; |
| import { IHeaders } from './IHeaders'; | ||
| export declare type FetchType = (method: string, url: string, body?: object, requestHeaders?: IHeaders) => Promise<object>; |
| import { PureCollection, IType, PureModel, View } from '@datx/core'; | ||
| import { ParamArrayType } from '../enums/ParamArrayType'; | ||
| import { IFetchOptions } from './IFetchOptions'; | ||
| import { IResponseObject } from './IResponseObject'; | ||
| import { fetchInterceptor } from '../interceptors/fetch'; | ||
| import { Response } from '../Response'; | ||
| export interface IConfigType { | ||
| baseUrl: string; | ||
| paramArrayType: ParamArrayType; | ||
| encodeQueryString: boolean; | ||
| collection?: PureCollection; | ||
| type?: IType | typeof PureModel; | ||
| views?: Array<View>; | ||
| fetchReference?: typeof fetch; | ||
| serialize?: (options: IFetchOptions) => IFetchOptions; | ||
| parse?: (data: object, options: IResponseObject) => object; | ||
| fetchInterceptor: typeof fetchInterceptor; | ||
| Response: typeof Response; | ||
| } |
| import { View, PureCollection, IType, PureModel } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { HttpMethod } from '../enums/HttpMethod'; | ||
| export interface IFetchOptions { | ||
| url: string; | ||
| options?: IRequestOptions; | ||
| params?: object | null; | ||
| data?: string | object | FormData; | ||
| method: HttpMethod; | ||
| collection?: PureCollection; | ||
| skipCache?: boolean; | ||
| views?: Array<View>; | ||
| type?: IType | typeof PureModel; | ||
| } |
| export declare type IHeaders = Record<string, string>; |
| import { IFetchOptions } from './IFetchOptions'; | ||
| import { Response } from '../Response'; | ||
| import { INetworkHandler } from './INetworkHandler'; | ||
| import { PureModel } from '@datx/core'; | ||
| export declare type IInterceptor<T extends PureModel = PureModel> = (request: IFetchOptions, next?: INetworkHandler) => Promise<Response<T>>; |
| import { BaseRequest } from '../BaseRequest'; | ||
| export declare type IModelNetworkConfig = BaseRequest | { | ||
| getMany?: BaseRequest; | ||
| getOne?: BaseRequest; | ||
| create?: BaseRequest; | ||
| update?: BaseRequest; | ||
| destroy?: BaseRequest; | ||
| }; |
| import { PureModel, PureCollection, IType } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { Response } from '../Response'; | ||
| import { INetworkModel } from './INetworkModel'; | ||
| import { INetworkModelConstructor } from './INetworkModelConstructor'; | ||
| export interface INetworkCollection extends PureCollection { | ||
| getOne<T extends INetworkModel = INetworkModel>(type: IType | INetworkModelConstructor, id: string, options?: IRequestOptions): Promise<Response<T>>; | ||
| getMany<T extends INetworkModel = INetworkModel>(type: IType | INetworkModelConstructor, options?: IRequestOptions): Promise<Response<T>>; | ||
| removeOne(type: IType | typeof PureModel, id: string, options?: boolean | IRequestOptions): Promise<void>; | ||
| removeOne(model: INetworkModel, options?: boolean | IRequestOptions): Promise<void>; | ||
| } |
| import { PureCollection, IRawModel, IRawCollection } from '@datx/core'; | ||
| import { INetworkCollection } from './INetworkCollection'; | ||
| export interface INetworkCollectionConstructor extends PureCollection { | ||
| new (data?: Array<IRawModel> | IRawCollection): INetworkCollection; | ||
| } |
| import { IFetchOptions } from './IFetchOptions'; | ||
| import { PureModel } from '@datx/core'; | ||
| import { Response } from '../Response'; | ||
| export declare type INetworkHandler<T extends PureModel = PureModel> = (request: IFetchOptions) => Promise<Response<T>>; |
| import { PureModel } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| export interface INetworkModel extends PureModel { | ||
| save(options?: IRequestOptions): Promise<INetworkModel>; | ||
| destroy(options?: IRequestOptions): Promise<void>; | ||
| } |
| import { INetworkModel } from './INetworkModel'; | ||
| import { IModelNetworkConfig } from './IModelNetworkConfig'; | ||
| import { IModelConstructor } from '@datx/core'; | ||
| export interface INetworkModelConstructor extends IModelConstructor { | ||
| network?: IModelNetworkConfig; | ||
| new (): INetworkModel; | ||
| } |
| import { View } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { Response } from '../Response'; | ||
| import { INetworkModel } from './INetworkModel'; | ||
| export interface INetworkView<T extends INetworkModel = INetworkModel> extends View<T> { | ||
| sync(body?: Response<T>): T | Array<T> | null; | ||
| getOne(id: string, options?: IRequestOptions): Promise<Response<T>>; | ||
| getMany(options?: IRequestOptions): Promise<Response<T>>; | ||
| } |
| import { BaseRequest } from '../BaseRequest'; | ||
| export declare type IPipeOperator = (request: BaseRequest) => void; |
| import { IHeaders } from './IHeaders'; | ||
| import { CachingStrategy } from '../enums/CachingStrategy'; | ||
| export interface IRequestOptions { | ||
| query?: Record<string, string | Array<string> | object>; | ||
| cacheOptions?: { | ||
| cachingStrategy?: CachingStrategy; | ||
| maxAge?: number; | ||
| skipCache?: boolean; | ||
| }; | ||
| networkConfig?: { | ||
| headers?: IHeaders; | ||
| }; | ||
| } |
| import { View } from '@datx/core'; | ||
| import { IResponseHeaders } from '@datx/utils'; | ||
| import { IHeaders } from './IHeaders'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { IResponseObject } from './IResponseObject'; | ||
| export interface IResponseInternal { | ||
| headers?: IResponseHeaders; | ||
| requestHeaders?: IHeaders; | ||
| error?: Array<string | object> | Error; | ||
| status?: number; | ||
| options?: IRequestOptions; | ||
| response: IResponseObject; | ||
| views: Array<View>; | ||
| } |
| import { PureCollection, IType, PureModel } from '@datx/core'; | ||
| import { IResponseHeaders } from '@datx/utils'; | ||
| import { IHeaders } from './IHeaders'; | ||
| export interface IResponseObject { | ||
| data?: object; | ||
| error?: Error; | ||
| headers?: IResponseHeaders; | ||
| requestHeaders?: IHeaders; | ||
| status?: number; | ||
| collection?: PureCollection; | ||
| type?: IType | typeof PureModel; | ||
| } |
| import { IRequestOptions } from './IRequestOptions'; | ||
| export interface IResponseSnapshot { | ||
| response: Omit<object, 'headers'> & { | ||
| headers?: Array<[string, string]>; | ||
| }; | ||
| options?: IRequestOptions; | ||
| } |
| import { BaseRequest } from './BaseRequest'; | ||
| import { IInterceptor } from './interfaces/IInterceptor'; | ||
| import { CachingStrategy } from './enums/CachingStrategy'; | ||
| import { HttpMethod } from './enums/HttpMethod'; | ||
| import { BodyType } from './enums/BodyType'; | ||
| import { ParamArrayType } from './enums/ParamArrayType'; | ||
| import { PureCollection, IType, PureModel } from '@datx/core'; | ||
| import { IResponseObject } from './interfaces/IResponseObject'; | ||
| import { IFetchOptions } from './interfaces/IFetchOptions'; | ||
| import { IRequestOptions } from './interfaces/IRequestOptions'; | ||
| export declare function setUrl(url: string, type?: IType | typeof PureModel): (pipeline: BaseRequest) => void; | ||
| export declare function addInterceptor(fn: IInterceptor, name?: string): (pipeline: BaseRequest) => void; | ||
| export declare function upsertInterceptor(fn: IInterceptor, name?: string): (pipeline: BaseRequest) => void; | ||
| export declare function removeInterceptor(name: string): (pipeline: BaseRequest) => void; | ||
| export declare function cache(strategy: CachingStrategy, maxAge?: number): (pipeline: BaseRequest) => void; | ||
| export declare function method(method: HttpMethod): (pipeline: BaseRequest) => void; | ||
| export declare function body(body: unknown, bodyType?: BodyType): (pipeline: BaseRequest) => void; | ||
| export declare function query(name: string, value: string | Array<string> | object | undefined): (pipeline: BaseRequest) => void; | ||
| export declare function query(params: Record<string, string | Array<string> | object | undefined>): (pipeline: BaseRequest) => void; | ||
| export declare function header(name: string, value: string): (pipeline: BaseRequest) => void; | ||
| export declare function header(params: Record<string, string>): (pipeline: BaseRequest) => void; | ||
| export declare function params(name: string, value: string): (pipeline: BaseRequest) => void; | ||
| export declare function params(params: Record<string, string>): (pipeline: BaseRequest) => void; | ||
| export declare function encodeQueryString(encodeQueryString: boolean): (pipeline: BaseRequest) => void; | ||
| export declare function paramArrayType(paramArrayType: ParamArrayType): (pipeline: BaseRequest) => void; | ||
| export declare function fetchReference(fetchReference: typeof fetch): (pipeline: BaseRequest) => void; | ||
| export declare function serializer(serialize: (request: IFetchOptions) => IFetchOptions): (pipeline: BaseRequest) => void; | ||
| export declare function parser(parse: (data: object, response: IResponseObject) => object): (pipeline: BaseRequest) => void; | ||
| export declare function collection(collection?: PureCollection): (pipeline: BaseRequest) => void; | ||
| export declare function requestOptions(options?: IRequestOptions): (pipeline: BaseRequest) => void; |
| import { PureModel, PureCollection, View } from '@datx/core'; | ||
| import { IHeaders } from './interfaces/IHeaders'; | ||
| import { IResponseInternal } from './interfaces/IResponseInternal'; | ||
| import { IResponseSnapshot } from './interfaces/IResponseSnapshot'; | ||
| import { IResponseObject } from './interfaces/IResponseObject'; | ||
| import { IResponseHeaders } from '@datx/utils'; | ||
| export declare class Response<T extends PureModel | Array<PureModel>> { | ||
| protected __data: any; | ||
| protected __internal: IResponseInternal; | ||
| /** | ||
| * Headers received from the API call | ||
| * | ||
| * @type {IResponseHeaders} | ||
| * @memberOf Response | ||
| */ | ||
| get headers(): IResponseHeaders | undefined; | ||
| /** | ||
| * Headers sent to the server | ||
| * | ||
| * @type {IHeaders} | ||
| * @memberOf Response | ||
| */ | ||
| get requestHeaders(): IHeaders | undefined; | ||
| /** | ||
| * Request error | ||
| * | ||
| * @type {(Array<JsonApi.IError>|Error)} | ||
| * @memberOf Response | ||
| */ | ||
| get error(): Array<string | object> | Error | undefined; | ||
| /** | ||
| * Received HTTP status | ||
| * | ||
| * @type {number} | ||
| * @memberOf Response | ||
| */ | ||
| get status(): number | undefined; | ||
| get views(): Array<View>; | ||
| /** | ||
| * Related Store | ||
| * | ||
| * @type {PureCollection} | ||
| * @memberOf Response | ||
| */ | ||
| readonly collection?: PureCollection; | ||
| /** | ||
| * Cache used for the link requests | ||
| * | ||
| * @protected | ||
| * @type {Record<string, Promise<Response>>} | ||
| * @memberOf Response | ||
| */ | ||
| protected readonly __cache: Record<string, () => Promise<Response<T>>>; | ||
| get isSuccess(): boolean; | ||
| get data(): T | null; | ||
| constructor(response: IResponseObject, collection?: PureCollection, overrideData?: T, views?: Array<View>); | ||
| private __updateInternal; | ||
| /** | ||
| * Replace the response record with a different record. Used to replace a record while keeping the same reference | ||
| * | ||
| * @param {PureModel} data New data | ||
| * @returns {Response} | ||
| * | ||
| * @memberOf Response | ||
| */ | ||
| replaceData(data: T): Response<T>; | ||
| clone(): Response<T>; | ||
| get snapshot(): IResponseSnapshot; | ||
| update(response: IResponseObject | Response<T>, views?: Array<View>): Response<T>; | ||
| } |
| import { PureCollection, PureModel, View } from '@datx/core'; | ||
| import { INetworkModel } from './interfaces/INetworkModel'; | ||
| import { INetworkView } from './interfaces/INetworkView'; | ||
| import { BaseRequest } from './BaseRequest'; | ||
| import { INetworkCollectionConstructor } from './interfaces/INetworkCollectionConstructor'; | ||
| interface INetwork<T> { | ||
| network?: BaseRequest; | ||
| new (): T; | ||
| } | ||
| export declare function withNetwork<T extends typeof PureModel>(Base: T): T & INetwork<INetworkModel>; | ||
| export declare function withNetwork<T extends typeof PureCollection>(Base: T): T & INetworkCollectionConstructor; | ||
| export declare function withNetwork<T extends typeof View>(Base: T): T & INetwork<INetworkView>; | ||
| export {}; |
+7
-49
| { | ||
| "name": "@datx/network", | ||
| "version": "3.0.0-beta.0", | ||
| "version": "3.0.0-beta.1", | ||
| "description": "DatX network layer", | ||
| "main": "dist/index.cjs.js", | ||
| "module": "dist/index.esm.js", | ||
| "typings": "dist/index.d.ts", | ||
| "main": "./index.cjs.js", | ||
| "module": "./index.esm.js", | ||
| "typings": "./index.d.ts", | ||
| "sideEffects": false, | ||
@@ -22,49 +22,7 @@ "repository": { | ||
| ], | ||
| "devDependencies": { | ||
| "@rollup/plugin-commonjs": "^21.0.0", | ||
| "@rollup/plugin-node-resolve": "^13.0.0", | ||
| "@rollup/plugin-typescript": "^8.2.1", | ||
| "@types/jest": "^27.0.0", | ||
| "@types/node": "^17.0.4", | ||
| "@types/react": "^18.0.0", | ||
| "jest": "^27.0.5", | ||
| "rollup": "^2.38.0", | ||
| "rollup-plugin-exclude-dependencies-from-bundle": "^1.1.17", | ||
| "rollup-plugin-terser": "^7.0.2", | ||
| "ts-jest": "^27.0.3", | ||
| "tslib": "~2.3.0", | ||
| "typescript": "~4.6.3" | ||
| }, | ||
| "scripts": { | ||
| "test": "jest --coverage", | ||
| "watch": "jest --watch --coverage", | ||
| "prepublish": "npm run build", | ||
| "build": "rollup -c" | ||
| }, | ||
| "jest": { | ||
| "coveragePathIgnorePatterns": [ | ||
| "/test/", | ||
| "/node_modules/" | ||
| ], | ||
| "moduleFileExtensions": [ | ||
| "ts", | ||
| "js" | ||
| ], | ||
| "testEnvironment": "jsdom", | ||
| "testRegex": "test/(.*).test.ts$", | ||
| "globals": { | ||
| "ts-jest": { | ||
| "diagnostics": { | ||
| "warnOnly": true | ||
| } | ||
| } | ||
| }, | ||
| "preset": "ts-jest", | ||
| "testMatch": null | ||
| }, | ||
| "dependencies": { | ||
| "@datx/core": "3.0.0-beta.0", | ||
| "@datx/utils": "3.0.0-beta.0" | ||
| "@datx/core": "3.0.0-beta.1", | ||
| "@datx/utils": "3.0.0-beta.1" | ||
| }, | ||
| "gitHead": "dfa9ed0f10d2a73b56a8eeed46133b375ef07554" | ||
| "gitHead": "20e52d35a1bc98fba5803d7787f568c481b81941" | ||
| } |
+8
-1
@@ -112,2 +112,9 @@ # @datx/network | ||
| <img src="https://infinum.com/infinum.png" width="264"> | ||
| <p align="center"> | ||
| <a href='https://infinum.com'> | ||
| <picture> | ||
| <source srcset="https://assets.infinum.com/brand/logo/static/white.svg" media="(prefers-color-scheme: dark)"> | ||
| <img src="https://assets.infinum.com/brand/logo/static/default.svg"> | ||
| </picture> | ||
| </a> | ||
| </p> |
| import { PureModel } from '@datx/core'; | ||
| import { IInterceptor } from './interfaces/IInterceptor'; | ||
| import { IPipeOperator } from './interfaces/IPipeOperator'; | ||
| import { Response } from './Response'; | ||
| import { BodyType } from './enums/BodyType'; | ||
| export declare class BaseRequest<TModel extends PureModel = PureModel, TParams extends object = {}> { | ||
| private _config; | ||
| private _options; | ||
| interceptors: Array<{ | ||
| name: string; | ||
| fn: IInterceptor<TModel>; | ||
| }>; | ||
| constructor(baseUrl: string); | ||
| pipe<TNewModel extends PureModel | Array<PureModel> = TModel, TNewParams extends object = TParams>(...operators: Array<IPipeOperator | undefined>): BaseRequest<TNewModel, TNewParams>; | ||
| private processBody; | ||
| fetch(params?: TParams | null, queryParams?: Record<string, string | Array<string> | object> | null, body?: any, bodyType?: BodyType): Promise<Response<TModel>>; | ||
| clone<TNewModel extends PureModel = TModel, TNewParams extends object = TParams>(BaseRequestConstructor?: typeof BaseRequest): BaseRequest<TNewModel, TNewParams>; | ||
| } |
| export declare const NETWORK_PERSISTED = "networkPersisted"; |
| import { PureCollection } from '@datx/core'; | ||
| import { INetworkCollectionConstructor } from './interfaces/INetworkCollectionConstructor'; | ||
| export declare function decorateCollection(BaseClass: typeof PureCollection): INetworkCollectionConstructor; |
| import { PureModel } from '@datx/core'; | ||
| import { INetworkModelConstructor } from './interfaces/INetworkModelConstructor'; | ||
| export declare function decorateModel(BaseClass: typeof PureModel): INetworkModelConstructor; |
| import { IConfigType } from './interfaces/IConfigType'; | ||
| export declare function getDefaultConfig(): IConfigType; |
| export declare enum BodyType { | ||
| Raw = 0, | ||
| Json = 1, | ||
| Multipart = 2, | ||
| Urlencoded = 3 | ||
| } |
| export declare enum CachingStrategy { | ||
| NetworkOnly = 1, | ||
| NetworkFirst = 2, | ||
| StaleWhileRevalidate = 3, | ||
| CacheOnly = 4, | ||
| CacheFirst = 5, | ||
| StaleAndUpdate = 6 | ||
| } |
| export declare enum HttpMethod { | ||
| Get = "GET", | ||
| Post = "POST", | ||
| Put = "PUT", | ||
| Patch = "Patch", | ||
| Delete = "Delete", | ||
| Options = "Options", | ||
| Head = "Head" | ||
| } |
| export declare enum ParamArrayType { | ||
| MultipleParams = 0, | ||
| CommaSeparated = 1, | ||
| ParamArray = 2 | ||
| } |
| import { INetworkModel } from '../interfaces/INetworkModel'; | ||
| import { IRequestOptions } from '../interfaces/IRequestOptions'; | ||
| export declare function saveModel<TModel extends INetworkModel>(model: TModel, options?: IRequestOptions): Promise<TModel>; | ||
| export declare function removeModel<TModel extends INetworkModel>(model: TModel, options?: IRequestOptions): Promise<void>; |
| import { ParamArrayType } from '../enums/ParamArrayType'; | ||
| import { PureModel, IReferenceDefinition } from '@datx/core'; | ||
| export declare const isBrowser: boolean; | ||
| export declare function deepCopy<T extends object>(inObject: T): T; | ||
| export declare function interpolateParams(url: string, params: Record<string, string>): string; | ||
| export declare function appendQueryParams(url: string, query: Record<string, string | Array<string> | object>, paramArrayType: ParamArrayType, encodeQueryString: boolean): string; | ||
| export declare function getModelClassRefs(type: typeof PureModel | PureModel): Record<string, IReferenceDefinition>; |
| "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@datx/utils"),t=require("@datx/core"),n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)};function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function o(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}var r,i=function(){return i=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};function a(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}exports.ParamArrayType=void 0,(r=exports.ParamArrayType||(exports.ParamArrayType={}))[r.MultipleParams=0]="MultipleParams",r[r.CommaSeparated=1]="CommaSeparated",r[r.ParamArray=2]="ParamArray";var s="undefined"!=typeof window;function c(e){var t,n;if("object"!=typeof e||null===e)return e;var o=Array.isArray(e)?[]:{};for(n in e)t=e[n],o[n]=c(t);return o}var u=/\{\s*([a-zA-Z0-9\-_]+)\s*\}/g;function l(e,t,n){void 0===n&&(n="");var o=[];return Object.keys(t).forEach((function(r){var i="".concat(n).concat(n?"[".concat(r,"]"):r);t[r]instanceof Array?e===exports.ParamArrayType.CommaSeparated?o.push({key:i,value:t[r].join(",")}):e===exports.ParamArrayType.MultipleParams?o.push.apply(o,t[r].map((function(e){return{key:i,value:e}}))):e===exports.ParamArrayType.ParamArray&&o.push.apply(o,t[r].map((function(e){return{key:"".concat(i,"[]"),value:e}}))):"object"==typeof t[r]?o.push.apply(o,l(e,t[r],i)):void 0!==t[r]&&o.push({key:i,value:t[r]})})),o}function p(e,t,n,o){return function(e,t){var n=e;if(t.length){var o="";-1===n.indexOf("?")?o="?":n.endsWith("&")||n.endsWith("?")||(o="&"),n+=o+t.join("&")}return n}(e,l(n,t).map((function(e){var t=e.key,n=e.value;return{key:t,value:o?encodeURIComponent(n):n}})).map((function(e){var t=e.key,n=e.value;return"".concat(t,"=").concat(n)})))}function d(e){if(e instanceof Array)return e;var t=[];return e.forEach((function(e,n){t.push([n,e])})),t}function f(n,o,r){var i=null,a=Boolean(n.data&&Object.keys(n.data).length);if(o&&n.data&&a)i=r||(n.type?o.add(n.data,n.type):o.add(n.data));else if(a){var s=n.type===t.PureModel||Object.isPrototypeOf.call(t.PureModel,n.type||{})?n.type:t.PureModel;return{value:i=r||e.mapItems(n.data,(function(e){return new s(e)}))}}return new t.Bucket.ToOneOrMany(i,o,!0)}var h,y,v=function(){function n(e,t,n,o){var r=this;this.__internal={response:{},views:[]},this.__cache={},this.collection=t,this.__updateInternal(e,o);try{this.__data=f(e,t,n)}catch(e){this.__internal.error=e}if(this.views.forEach((function(e){r.__data.value&&e.add(r.__data.value)})),Object.freeze(this),this.error)throw this}return Object.defineProperty(n.prototype,"headers",{get:function(){return this.__internal.headers},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"requestHeaders",{get:function(){return this.__internal.requestHeaders},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"error",{get:function(){return this.__internal.error},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"status",{get:function(){return this.__internal.status},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"views",{get:function(){return this.__internal.views},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isSuccess",{get:function(){return!this.error},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"data",{get:function(){return this.__data.value},enumerable:!1,configurable:!0}),n.prototype.__updateInternal=function(t,n){var o;this.__internal.response=t,this.__internal.headers=t.headers&&((o=t.headers)instanceof Array?new e.Headers(o):o),this.__internal.requestHeaders=t.requestHeaders,this.__internal.error=t.error,this.__internal.status=t.status,n&&(this.__internal.views=n),this.error||this.status||(this.__internal.error=new Error("Network not available"))},n.prototype.replaceData=function(e){var o=this.data;if(o===e)return this;var r=t.getModelId(o).toString(),i=t.getModelType(o),a=this.views.map((function(e){return e.list.indexOf(o)}));return this.collection&&(this.collection.removeOne(i,r),this.collection.add(e)),t.updateModel(e,t.modelToJSON(o)),t.updateModelId(e,r),this.views.forEach((function(t,n){-1!==a[n]&&(t.list[a[n]]=e)})),new n(this.__internal.response,this.collection,e)},n.prototype.clone=function(){return new n(this.__internal.response,this.collection,this.data||void 0)},Object.defineProperty(n.prototype,"snapshot",{get:function(){return{response:Object.assign({},this.__internal.response,{headers:this.__internal.response.headers&&d(this.__internal.response.headers),collection:void 0})}},enumerable:!1,configurable:!0}),n.prototype.update=function(e,t){var o=e instanceof n?e.__internal.response:e;this.__updateInternal(o,t);var r=f(o,this.collection);return this.__data.__readonlyValue=r.value,this},n}();function g(e,t){return e.data?i(i({},e),{data:t(e.data,e)}):e}function _(e,t,n,o){return void 0===t&&(t=function(e){return e}),void 0===n&&(n=function(e){return e}),void 0===o&&(o=v),function(r,i){var a,s;if(!e)throw new Error("The fetch reference must be defined");var c,u,l=t?t(r):r,p=0,d=l.method.toUpperCase(),f="GET"!==d&&"HEAD"!==d,h="object"!=typeof l.data||l.data instanceof FormData?l.data:JSON.stringify(l.data),y=f?h:void 0,v=Object.assign({},null===(s=null===(a=l.options)||void 0===a?void 0:a.networkConfig)||void 0===s?void 0:s.headers),_=Object.assign({body:y,headers:v,method:l.method});return e(l.url,_).then((function(e){return p=e.status,u=e.headers,e.json()})).catch((function(e){if(204===p)return null;if(0===p)throw new Error("Network not available");throw e})).then((function(e){if(c=e,p>=400)throw{message:"Invalid HTTP status: ".concat(p),status:p};var t=g({data:c,headers:u,requestHeaders:v,status:p,collection:r.collection,type:r.type},n);return new o(t,r.collection,void 0,r.views)})).catch((function(e){var t=g({data:c,error:e,headers:u,requestHeaders:v,status:p,collection:r.collection,type:r.type},n);throw new o(t,r.collection,void 0,r.views)}))}}exports.HttpMethod=void 0,(h=exports.HttpMethod||(exports.HttpMethod={})).Get="GET",h.Post="POST",h.Put="PUT",h.Patch="Patch",h.Delete="Delete",h.Options="Options",h.Head="Head",exports.CachingStrategy=void 0,(y=exports.CachingStrategy||(exports.CachingStrategy={}))[y.NetworkOnly=1]="NetworkOnly",y[y.NetworkFirst=2]="NetworkFirst",y[y.StaleWhileRevalidate=3]="StaleWhileRevalidate",y[y.CacheOnly=4]="CacheOnly",y[y.CacheFirst=5]="CacheFirst",y[y.StaleAndUpdate=6]="StaleAndUpdate";var w,m=[];function b(e){m=m.filter((function(t){return!t.types.includes(e)}))}function O(n,o,r,i){return void 0===r&&(r=!1),o(n).then((function(o){var a=o;return i&&(a=i.update(o,n.views)),r&&function(n,o){if(o&&o.isSuccess&&(o.data||null===o.data)){var r=e.mapItems(o.data||[],t.getModelType);(m=m.filter((function(e){return e.url!==n}))).unshift({response:o.snapshot,collection:o.collection,time:Date.now(),types:[].concat(r),url:n})}}(n.url,a),a}),(function(e){throw e}))}function k(e,t,n){var o,r;return new v({error:new Error(e),collection:n,requestHeaders:null===(r=null===(o=t.options)||void 0===o?void 0:o.networkConfig)||void 0===r?void 0:r.headers},n)}function x(e,t){return void 0===t&&(t=1/0),function(n,o){var r,i,a,s,c;if(!o)throw new Error("Cache interceptor can't be the last interceptor");var u=n.method.toUpperCase()===exports.HttpMethod.Get,l=(null===(i=null===(r=n.options)||void 0===r?void 0:r.cacheOptions)||void 0===i?void 0:i.skipCache)||!u?exports.CachingStrategy.NetworkOnly:(null===(s=null===(a=n.options)||void 0===a?void 0:a.cacheOptions)||void 0===s?void 0:s.cachingStrategy)||e;if(l===exports.CachingStrategy.NetworkOnly)return O(n,o);var p=function(e,t){var n=Date.now()-1e3*t,o=m.find((function(t){return t.url===e&&t.time>n}));if(o){var r=o.response;return{response:new v(r.response,o.collection,r.options),time:o.time,types:o.types,url:o.url}}}(n.url,t);if(l===exports.CachingStrategy.NetworkFirst)return O(n,o,!0).catch((function(e){if(p)return p.response;throw e}));if(l===exports.CachingStrategy.StaleWhileRevalidate){var d=O(n,o,!0);return p?(d.catch((function(){})),Promise.resolve(p.response)):d}if(l===exports.CachingStrategy.CacheOnly)return p?Promise.resolve(p.response):Promise.reject(k("No cache for this request",n,null==n?void 0:n.collection));if(l===exports.CachingStrategy.CacheFirst)return p?Promise.resolve(p.response):O(n,o,!0);if(l===exports.CachingStrategy.StaleAndUpdate){var f=null===(c=null==p?void 0:p.response)||void 0===c?void 0:c.clone();return d=O(n,o,!0,f),f?(d.catch((function(){})),Promise.resolve(f)):d}return Promise.reject(k("Invalid caching strategy",n,null==n?void 0:n.collection))}}function P(e,n){return void 0===n&&(n=t.PureModel),function(t){t._options.url=e,t._config.type=n}}function T(e,t){return void 0===t&&(t=e.name),function(n){var o=n.interceptors.find((function(e){return e.name===t}));o?o.fn=e:n.interceptors.push({name:t,fn:e})}}function M(e,t){return void 0===t&&(t=1/0),T(x(e,t),"cache")}function C(e){return function(t){t._options.method=e}}function S(e,t){return function(n){t||0===t?n._options.bodyType=t:e instanceof FormData?n._options.bodyType=w.Multipart:n._options.bodyType="object"==typeof e?w.Json:w.Raw,n._options.body=e}}function j(e,t){return function(n){"string"==typeof e?n._options.query[e]=t:Object.assign(n._options.query,e)}}function A(e,t){return function(n){"string"==typeof e?n._options.headers[e]=t||"":Object.assign(n._options.headers,e)}}function E(e){return function(t){var n,o,r,i,a;(null==e?void 0:e.query)&&j(null==e?void 0:e.query)(t),(null===(n=null==e?void 0:e.networkConfig)||void 0===n?void 0:n.headers)&&A(null===(o=null==e?void 0:e.networkConfig)||void 0===o?void 0:o.headers)(t),(null===(r=null==e?void 0:e.cacheOptions)||void 0===r?void 0:r.cachingStrategy)&&M(null===(i=null==e?void 0:e.cacheOptions)||void 0===i?void 0:i.cachingStrategy,null===(a=null==e?void 0:e.cacheOptions)||void 0===a?void 0:a.maxAge)(t)}}!function(e){e[e.Raw=0]="Raw",e[e.Json=1]="Json",e[e.Multipart=2]="Multipart",e[e.Urlencoded=3]="Urlencoded"}(w||(w={}));var q=function(){function n(n){var o,r;this._config={baseUrl:"/",encodeQueryString:!0,paramArrayType:exports.ParamArrayType.ParamArray,fetchReference:s?null===(r=null===(o=window.fetch)||void 0===o?void 0:o.bind)||void 0===r?void 0:r.call(o,window):void 0,fetchInterceptor:_,serialize:function(n){return i(i({},n),{data:e.mapItems(n.data,(function(e){return e instanceof t.PureModel?t.modelToJSON(e):e}))||void 0})},Response:v},this._options={method:exports.HttpMethod.Get,headers:{},query:{},params:{},bodyType:w.Json},this.interceptors=[{fn:_(this._config.fetchReference,this._config.serialize,this._config.parse),name:"fetch"},{fn:x(s?exports.CachingStrategy.CacheFirst:exports.CachingStrategy.NetworkOnly),name:"cache"}],this._config.baseUrl=n}return n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.clone();return e.filter(Boolean).forEach((function(e){return e(n)})),n},n.prototype.processBody=function(){if(this._options.body)return this._options.bodyType===w.Json?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/json",this._options.body):this._options.bodyType===w.Urlencoded?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/x-www-form-urlencoded","string"==typeof this._options.body?this._options.body:p("",this._options.body,this._config.paramArrayType,this._config.encodeQueryString).slice(1)):this._options.bodyType===w.Multipart?(this._options.headers["content-type"]=this._options.headers["content-type"]||"multipart/form-data",this._options.body instanceof FormData?this._options.body:new FormData(this._options.body)):this._options.body},n.prototype.fetch=function(e,t,n,o){var r=void 0===n?this:this.pipe(S(n,o));if(!r._options.url)throw new Error("URL should be defined");var i=Object.assign({},r._options.params,e||{}),a=function(e,t){for(var n=e,o=u.exec(n),r=0;o;){var i=t[o[1]];void 0===i&&(i=o[0],r=u.lastIndex),n=n.replace(o[0],i),u.lastIndex=r,o=u.exec(n)}return n}("".concat(r._config.baseUrl).concat(r._options.url),i),s={url:p(a,Object.assign({},r._options.query,t),r._config.paramArrayType,r._config.encodeQueryString),method:r._options.method,data:r.processBody(),collection:r._config.collection,params:e,options:{networkConfig:{headers:r._options.headers}},views:r._config.views,type:r._config.type},c=r.interceptors.reduce((function(e,t){return function(n){return t.fn(n,e)}}),void 0);if(!c)throw new Error("Something went wrong");return c(s)},n.prototype.clone=function(e){void 0===e&&(e=this.constructor);var t=new e(this._config.baseUrl);return t.interceptors=c(this.interceptors),t._config=c(this._config),t._options=c(this._options),t._config.collection=this._config.collection,t._config.fetchInterceptor=this._config.fetchInterceptor,t._config.fetchReference=this._config.fetchReference,t._config.Response=this._config.Response,t._config.type=this._config.type,t},n}();function R(e,t){return e.pipe(E(t))}var I=["networkPersisted"];exports.BaseRequest=q,exports.Response=v,exports.addInterceptor=function(e,t){return void 0===t&&(t=e.name),function(n){n.interceptors=n.interceptors.filter((function(e){return e.name!==t})),n.interceptors.push({name:t,fn:e})}},exports.body=S,exports.cache=M,exports.clearAllCache=function(){m.length=0},exports.clearCacheByType=b,exports.collection=function(e){return function(t){t._config.collection=e}},exports.encodeQueryString=function(e){return function(t){t._config.encodeQueryString=e}},exports.fetchReference=function(e){return function(t){var n=t._config;n.fetchReference=e,T(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}},exports.header=A,exports.method=C,exports.paramArrayType=function(e){return function(t){t._config.paramArrayType=e}},exports.params=function(e,t){return function(n){"string"==typeof e?n._options.params[e]=t:Object.assign(n._options.params,e)}},exports.parser=function(e){return function(t){var n=t._config;n.parse=e,T(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}},exports.query=j,exports.requestOptions=E,exports.serializer=function(e){return function(t){var n=t._config;n.serialize=e,T(n.fetchInterceptor(n.fetchReference,n.serialize,n.parse,n.Response),"fetch")(t)}},exports.setUrl=P,exports.upsertInterceptor=T,exports.withNetwork=function(n){if(t.isModel(n))return function(n){function r(t,o){void 0===t&&(t={});var r=n.call(this,t,o)||this,i=(null==t?void 0:t[e.META_FIELD])||{};return I.forEach((function(t){t in i&&e.setMeta(r,t,i[t])})),r}return o(r,n),r.prototype.save=function(n){return function(n,o){var r,i,a,s,c,u=n.constructor;if(!u.network)throw new Error("The network property needs to be defined on the model");var l,p,d=e.getMeta(n,"networkPersisted",!1);if(!(l=u.network instanceof q?d?u.network.pipe(C(exports.HttpMethod.Put),P("".concat(u.network._options.url,"/{id}"),u)):u.network.pipe(C(exports.HttpMethod.Post)):d?u.network.update:u.network.create))throw new Error("The base request has not been defined");return l.pipe((null==o?void 0:o.query)&&j(null==o?void 0:o.query),(null===(r=null==o?void 0:o.networkConfig)||void 0===r?void 0:r.headers)&&A(null===(i=null==o?void 0:o.networkConfig)||void 0===i?void 0:i.headers),(null===(a=null==o?void 0:o.cacheOptions)||void 0===a?void 0:a.cachingStrategy)&&M(null===(s=null==o?void 0:o.cacheOptions)||void 0===s?void 0:s.cachingStrategy,null===(c=null==o?void 0:o.cacheOptions)||void 0===c?void 0:c.maxAge),S(n)).fetch({id:t.getModelId(n)}).then((p=n,function(n){if(n.error)throw n.error;if(204===n.status)return e.setMeta(p,"networkPersisted",!0),p;e.setMeta(p,"networkPersisted",!0);var o=n.replaceData(p).data||p;return t.commitModel(o),o}))}(this,n)},r.prototype.destroy=function(n){return function(n,o){var r,i,a,s,c,u=n.constructor;if(!u.network)throw new Error("The network property needs to be defined on the model");var l,p=e.getMeta(n,"networkPersisted",!1);if(!(l=u.network instanceof q?!!p&&u.network.pipe(C(exports.HttpMethod.Delete),P("".concat(u.network._options.url,"/{id}"),u)):!!p&&u.network.destroy)&&!1!==l)throw new Error("The base request has not been defined");return l&&l.pipe((null==o?void 0:o.query)&&j(null==o?void 0:o.query),(null===(r=null==o?void 0:o.networkConfig)||void 0===r?void 0:r.headers)&&A(null===(i=null==o?void 0:o.networkConfig)||void 0===i?void 0:i.headers),(null===(a=null==o?void 0:o.cacheOptions)||void 0===a?void 0:a.cachingStrategy)&&M(null===(s=null==o?void 0:o.cacheOptions)||void 0===s?void 0:s.cachingStrategy,null===(c=null==o?void 0:o.cacheOptions)||void 0===c?void 0:c.maxAge)).fetch({id:t.getModelId(n)}).then((function(){var e=t.getModelCollection(n);e&&e.removeOne(n)})),Promise.resolve()}(this,n)},r}(n);if(t.isCollection(n))return function(e){function n(t){void 0===t&&(t=[]);var n,o,r=e.call(this,t)||this;return t instanceof Array||!(null==t?void 0:t.cache)||(n=t.cache,o=r,m.push.apply(m,a(a([],m,!1),n.map((function(e){return Object.assign({collection:o},e)})),!1))),r}return o(n,e),n.prototype.getConstructor=function(e){var n=this.constructor,o=t.getModelType(e);return n.types.find((function(e){return t.getModelType(e)===o}))||n.defaultModel},n.prototype.getOne=function(e,t,n){var o=this.getConstructor(e);if(!o||!o.network)throw new Error("The network configuration is wrong for the given model");if(o.network instanceof q)return o.network.pipe(E(n),P("".concat(o.network._options.url,"/{id}"),o)).fetch({id:t});if(!o.network.getOne)throw new Error("The getOne network request was not defined on the given model");return R(o.network.getOne,n).fetch({id:t})},n.prototype.getMany=function(e,t){var n=this.getConstructor(e);if(!n||!n.network)throw new Error("The network configuration is wrong for the given model");if(n.network instanceof q)return R(n.network,t).fetch();if(!n.network.getMany)throw new Error("The getMany network request was not defined on the given model");return R(n.network.getMany,t).fetch()},n.prototype.removeOne=function(n,o,r){var i=this,a=t.getModelType(n),s="object"!=typeof o&&void 0!==o&&"boolean"!=typeof o?o:null,c=null!==s?r:o,u=s?this.findOne(a,s):a;if(!u)throw new Error("The model was not found");return!1===c||void 0===c?Promise.resolve(e.prototype.removeOne.call(this,u)):(b(t.getModelType(n)),u.destroy("object"==typeof c?c:{}).then((function(){e.prototype.removeOne.call(i,u)})))},n.prototype.toJSON=function(){return Object.assign({},e.prototype.toJSON.call(this),{cache:(t=this,m.filter((function(e){return e.collection===t})).map((function(e){return Object.assign({},e,{collection:void 0})})))});var t},n}(n);throw new Error("The instance needs to be a model, collection or a view")}; |
| export { BaseRequest } from './BaseRequest'; | ||
| export { Response } from './Response'; | ||
| export { addInterceptor, cache, method, setUrl, body, query, header, params, fetchReference, encodeQueryString, paramArrayType, serializer, parser, collection, requestOptions, upsertInterceptor, } from './operators'; | ||
| export { IResponseHeaders } from '@datx/utils'; | ||
| export { clearAllCache, clearCacheByType } from './interceptors/cache'; | ||
| export { CachingStrategy } from './enums/CachingStrategy'; | ||
| export { HttpMethod } from './enums/HttpMethod'; | ||
| export { ParamArrayType } from './enums/ParamArrayType'; | ||
| export { IFetchOptions } from './interfaces/IFetchOptions'; | ||
| export { IHeaders } from './interfaces/IHeaders'; | ||
| export { IInterceptor } from './interfaces/IInterceptor'; | ||
| export { INetworkHandler } from './interfaces/INetworkHandler'; | ||
| export { IPipeOperator } from './interfaces/IPipeOperator'; | ||
| export { IResponseObject } from './interfaces/IResponseObject'; | ||
| export { withNetwork } from './withNetwork'; | ||
| export { INetworkCollection } from './interfaces/INetworkCollection'; | ||
| export { INetworkCollectionConstructor } from './interfaces/INetworkCollectionConstructor'; | ||
| export { INetworkModel } from './interfaces/INetworkModel'; | ||
| export { INetworkModelConstructor } from './interfaces/INetworkModelConstructor'; |
-1061
| import { Headers, mapItems, setMeta, getMeta, META_FIELD } from '@datx/utils'; | ||
| import { getModelId, getModelType, updateModel, modelToJSON, updateModelId, PureModel, Bucket, commitModel, getModelCollection, isModel, isCollection } from '@datx/core'; | ||
| /*! ***************************************************************************** | ||
| Copyright (c) Microsoft Corporation. | ||
| Permission to use, copy, modify, and/or distribute this software for any | ||
| purpose with or without fee is hereby granted. | ||
| THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
| REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
| AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
| INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
| LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
| OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
| PERFORMANCE OF THIS SOFTWARE. | ||
| ***************************************************************************** */ | ||
| /* global Reflect, Promise */ | ||
| var extendStatics = function(d, b) { | ||
| extendStatics = Object.setPrototypeOf || | ||
| ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
| function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | ||
| return extendStatics(d, b); | ||
| }; | ||
| function __extends(d, b) { | ||
| if (typeof b !== "function" && b !== null) | ||
| throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); | ||
| extendStatics(d, b); | ||
| function __() { this.constructor = d; } | ||
| d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | ||
| } | ||
| var __assign = function() { | ||
| __assign = Object.assign || function __assign(t) { | ||
| for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
| s = arguments[i]; | ||
| for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
| } | ||
| return t; | ||
| }; | ||
| return __assign.apply(this, arguments); | ||
| }; | ||
| function __spreadArray(to, from, pack) { | ||
| if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
| if (ar || !(i in from)) { | ||
| if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
| ar[i] = from[i]; | ||
| } | ||
| } | ||
| return to.concat(ar || Array.prototype.slice.call(from)); | ||
| } | ||
| var ParamArrayType; | ||
| (function (ParamArrayType) { | ||
| ParamArrayType[ParamArrayType["MultipleParams"] = 0] = "MultipleParams"; | ||
| ParamArrayType[ParamArrayType["CommaSeparated"] = 1] = "CommaSeparated"; | ||
| ParamArrayType[ParamArrayType["ParamArray"] = 2] = "ParamArray"; | ||
| })(ParamArrayType || (ParamArrayType = {})); | ||
| var isBrowser = typeof window !== 'undefined'; | ||
| function deepCopy(inObject) { | ||
| var value; | ||
| var key; | ||
| if (typeof inObject !== 'object' || inObject === null) { | ||
| return inObject; // Return the value if inObject is not an object | ||
| } | ||
| // Create an array or object to hold the values | ||
| var outObject = Array.isArray(inObject) ? [] : {}; | ||
| for (key in inObject) { | ||
| value = inObject[key]; | ||
| // Recursively (deep) copy for nested objects, including arrays | ||
| outObject[key] = deepCopy(value); | ||
| } | ||
| return outObject; | ||
| } | ||
| var interpolationRegex = /\{\s*([a-zA-Z0-9\-_]+)\s*\}/g; | ||
| function interpolateParams(url, params) { | ||
| var newUrl = url; | ||
| var match = interpolationRegex.exec(newUrl); | ||
| var lastIndex = 0; | ||
| while (match) { | ||
| var param = params[match[1]]; | ||
| if (param === undefined) { | ||
| param = match[0]; | ||
| lastIndex = interpolationRegex.lastIndex; | ||
| } | ||
| newUrl = newUrl.replace(match[0], param); | ||
| interpolationRegex.lastIndex = lastIndex; | ||
| match = interpolationRegex.exec(newUrl); | ||
| } | ||
| return newUrl; | ||
| } | ||
| function parametrize(paramArrayType, params, scope) { | ||
| if (scope === void 0) { scope = ''; } | ||
| var list = []; | ||
| Object.keys(params).forEach(function (key) { | ||
| var scoped = "".concat(scope).concat(scope ? "[".concat(key, "]") : key); | ||
| if (params[key] instanceof Array) { | ||
| if (paramArrayType === ParamArrayType.CommaSeparated) { | ||
| list.push({ key: scoped, value: params[key].join(',') }); | ||
| } | ||
| else if (paramArrayType === ParamArrayType.MultipleParams) { | ||
| list.push.apply(list, params[key].map(function (param) { return ({ key: scoped, value: param }); })); | ||
| } | ||
| else if (paramArrayType === ParamArrayType.ParamArray) { | ||
| list.push.apply(list, params[key].map(function (param) { return ({ | ||
| key: "".concat(scoped, "[]"), | ||
| value: param, | ||
| }); })); | ||
| } | ||
| } | ||
| else if (typeof params[key] === 'object') { | ||
| list.push.apply(list, parametrize(paramArrayType, params[key], scoped)); | ||
| } | ||
| else if (params[key] !== undefined) { | ||
| list.push({ key: scoped, value: params[key] }); | ||
| } | ||
| }); | ||
| return list; | ||
| } | ||
| function appendParams(url, params) { | ||
| var newUrl = url; | ||
| if (params.length) { | ||
| var separator = ''; | ||
| if (newUrl.indexOf('?') === -1) { | ||
| separator = '?'; | ||
| } | ||
| else if (!newUrl.endsWith('&') && !newUrl.endsWith('?')) { | ||
| separator = '&'; | ||
| } | ||
| newUrl += separator + params.join('&'); | ||
| } | ||
| return newUrl; | ||
| } | ||
| function appendQueryParams(url, query, paramArrayType, encodeQueryString) { | ||
| var processedParams = parametrize(paramArrayType, query) | ||
| .map(function (_a) { | ||
| var key = _a.key, value = _a.value; | ||
| return ({ | ||
| key: key, | ||
| value: encodeQueryString ? encodeURIComponent(value) : value, | ||
| }); | ||
| }) | ||
| .map(function (_a) { | ||
| var key = _a.key, value = _a.value; | ||
| return "".concat(key, "=").concat(value); | ||
| }); | ||
| return appendParams(url, processedParams); | ||
| } | ||
| function serializeHeaders(headers) { | ||
| if (headers instanceof Array) { | ||
| return headers; | ||
| } | ||
| var list = []; | ||
| headers.forEach(function (value, key) { | ||
| list.push([key, value]); | ||
| }); | ||
| return list; | ||
| } | ||
| function initHeaders(headers) { | ||
| if (headers instanceof Array) { | ||
| return new Headers(headers); | ||
| } | ||
| return headers; | ||
| } | ||
| function initData(response, collection, overrideData) { | ||
| var data = null; | ||
| var hasData = Boolean(response.data && Object.keys(response.data).length); | ||
| if (collection && response.data && hasData) { | ||
| data = | ||
| overrideData || | ||
| (response.type | ||
| ? collection.add(response.data, response.type) | ||
| : collection.add(response.data)); | ||
| } | ||
| else if (hasData) { | ||
| var ModelConstructor_1 = response.type === PureModel || Object.isPrototypeOf.call(PureModel, response.type || {}) | ||
| ? response.type | ||
| : PureModel; | ||
| data = overrideData || mapItems(response.data, function (item) { return new ModelConstructor_1(item); }); | ||
| return { value: data }; | ||
| } | ||
| return new Bucket.ToOneOrMany(data, collection, true); | ||
| } | ||
| var Response = /** @class */ (function () { | ||
| function Response(response, collection, overrideData, views) { | ||
| var _this = this; | ||
| this.__internal = { | ||
| response: {}, | ||
| views: [], | ||
| }; | ||
| /** | ||
| * Cache used for the link requests | ||
| * | ||
| * @protected | ||
| * @type {Record<string, Promise<Response>>} | ||
| * @memberOf Response | ||
| */ | ||
| this.__cache = {}; | ||
| this.collection = collection; | ||
| this.__updateInternal(response, views); | ||
| try { | ||
| this.__data = initData(response, collection, overrideData); | ||
| } | ||
| catch (e) { | ||
| this.__internal.error = e; | ||
| } | ||
| this.views.forEach(function (view) { | ||
| if (_this.__data.value) { | ||
| view.add(_this.__data.value); | ||
| } | ||
| }); | ||
| Object.freeze(this); | ||
| if (this.error) { | ||
| throw this; | ||
| } | ||
| } | ||
| Object.defineProperty(Response.prototype, "headers", { | ||
| /** | ||
| * Headers received from the API call | ||
| * | ||
| * @type {IResponseHeaders} | ||
| * @memberOf Response | ||
| */ | ||
| get: function () { | ||
| return this.__internal.headers; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Object.defineProperty(Response.prototype, "requestHeaders", { | ||
| /** | ||
| * Headers sent to the server | ||
| * | ||
| * @type {IHeaders} | ||
| * @memberOf Response | ||
| */ | ||
| get: function () { | ||
| return this.__internal.requestHeaders; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Object.defineProperty(Response.prototype, "error", { | ||
| /** | ||
| * Request error | ||
| * | ||
| * @type {(Array<JsonApi.IError>|Error)} | ||
| * @memberOf Response | ||
| */ | ||
| get: function () { | ||
| return this.__internal.error; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Object.defineProperty(Response.prototype, "status", { | ||
| /** | ||
| * Received HTTP status | ||
| * | ||
| * @type {number} | ||
| * @memberOf Response | ||
| */ | ||
| get: function () { | ||
| return this.__internal.status; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Object.defineProperty(Response.prototype, "views", { | ||
| get: function () { | ||
| return this.__internal.views; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Object.defineProperty(Response.prototype, "isSuccess", { | ||
| get: function () { | ||
| return !this.error; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Object.defineProperty(Response.prototype, "data", { | ||
| get: function () { | ||
| return this.__data.value; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Response.prototype.__updateInternal = function (response, views) { | ||
| this.__internal.response = response; | ||
| this.__internal.headers = response.headers && initHeaders(response.headers); | ||
| this.__internal.requestHeaders = response.requestHeaders; | ||
| this.__internal.error = response.error; | ||
| this.__internal.status = response.status; | ||
| if (views) { | ||
| this.__internal.views = views; | ||
| } | ||
| if (!this.error && !this.status) { | ||
| this.__internal.error = new Error('Network not available'); | ||
| } | ||
| }; | ||
| /** | ||
| * Replace the response record with a different record. Used to replace a record while keeping the same reference | ||
| * | ||
| * @param {PureModel} data New data | ||
| * @returns {Response} | ||
| * | ||
| * @memberOf Response | ||
| */ | ||
| Response.prototype.replaceData = function (data) { | ||
| var record = this.data; | ||
| if (record === data) { | ||
| return this; | ||
| } | ||
| var newId = getModelId(record).toString(); | ||
| var type = getModelType(record); | ||
| var viewIndexes = this.views.map(function (view) { return view.list.indexOf(record); }); | ||
| if (this.collection) { | ||
| this.collection.removeOne(type, newId); | ||
| this.collection.add(data); | ||
| } | ||
| updateModel(data, modelToJSON(record)); | ||
| updateModelId(data, newId); | ||
| this.views.forEach(function (view, index) { | ||
| if (viewIndexes[index] !== -1) { | ||
| view.list[viewIndexes[index]] = data; | ||
| } | ||
| }); | ||
| return new Response(this.__internal.response, this.collection, data); | ||
| }; | ||
| Response.prototype.clone = function () { | ||
| return new Response(this.__internal.response, this.collection, this.data || undefined); | ||
| }; | ||
| Object.defineProperty(Response.prototype, "snapshot", { | ||
| get: function () { | ||
| return { | ||
| response: Object.assign({}, this.__internal.response, { | ||
| headers: this.__internal.response.headers && serializeHeaders(this.__internal.response.headers), | ||
| collection: undefined, | ||
| }), | ||
| }; | ||
| }, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| Response.prototype.update = function (response, views) { | ||
| var responseData = response instanceof Response ? response.__internal.response : response; | ||
| this.__updateInternal(responseData, views); | ||
| var newData = initData(responseData, this.collection); | ||
| this.__data.__readonlyValue = newData.value; | ||
| return this; | ||
| }; | ||
| return Response; | ||
| }()); | ||
| function parseResponse(response, parse) { | ||
| if (response.data) { | ||
| return __assign(__assign({}, response), { data: parse(response.data, response) }); | ||
| } | ||
| return response; | ||
| } | ||
| function fetchInterceptor(fetchReference, serialize, parse, Response$1) { | ||
| if (serialize === void 0) { serialize = function (options) { return options; }; } | ||
| if (parse === void 0) { parse = function (data) { return data; }; } | ||
| if (Response$1 === void 0) { Response$1 = Response; } | ||
| return function (request, _next) { | ||
| var _a, _b; | ||
| if (!fetchReference) { | ||
| throw new Error('The fetch reference must be defined'); | ||
| } | ||
| var payload = serialize ? serialize(request) : request; | ||
| var data; | ||
| var status = 0; | ||
| var headers; | ||
| var uppercaseMethod = payload.method.toUpperCase(); | ||
| var isBodySupported = uppercaseMethod !== 'GET' && uppercaseMethod !== 'HEAD'; | ||
| var bodyContent = typeof payload.data === 'object' && !(payload.data instanceof FormData) | ||
| ? JSON.stringify(payload.data) | ||
| : payload.data; | ||
| var body = isBodySupported ? bodyContent : undefined; | ||
| var requestHeaders = Object.assign({}, (_b = (_a = payload.options) === null || _a === void 0 ? void 0 : _a.networkConfig) === null || _b === void 0 ? void 0 : _b.headers); | ||
| var options = Object.assign({ | ||
| body: body, | ||
| headers: requestHeaders, | ||
| method: payload.method, | ||
| }); | ||
| return fetchReference(payload.url, options) | ||
| .then(function (response) { | ||
| status = response.status; | ||
| headers = response.headers; | ||
| return response.json(); | ||
| }) | ||
| .catch(function (error) { | ||
| if (status === 204) { | ||
| return null; | ||
| } | ||
| if (status === 0) { | ||
| throw new Error('Network not available'); | ||
| } | ||
| throw error; | ||
| }) | ||
| .then(function (responseData) { | ||
| data = responseData; | ||
| if (status >= 400) { | ||
| throw { | ||
| message: "Invalid HTTP status: ".concat(status), | ||
| status: status, | ||
| }; | ||
| } | ||
| var response = parseResponse({ | ||
| data: data, | ||
| headers: headers, | ||
| requestHeaders: requestHeaders, | ||
| status: status, | ||
| collection: request.collection, | ||
| type: request.type, | ||
| }, parse); | ||
| return new Response$1(response, request.collection, undefined, request.views); | ||
| }) | ||
| .catch(function (error) { | ||
| var response = parseResponse({ | ||
| data: data, | ||
| error: error, | ||
| headers: headers, | ||
| requestHeaders: requestHeaders, | ||
| status: status, | ||
| collection: request.collection, | ||
| type: request.type, | ||
| }, parse); | ||
| throw new Response$1(response, request.collection, undefined, request.views); | ||
| }); | ||
| }; | ||
| } | ||
| function getDefaultConfig() { | ||
| var _a, _b; | ||
| return { | ||
| // Base URL for all API calls | ||
| baseUrl: '/', | ||
| encodeQueryString: true, | ||
| // Determines how will the request param arrays be stringified | ||
| paramArrayType: ParamArrayType.ParamArray, | ||
| fetchReference: isBrowser ? (_b = (_a = window.fetch) === null || _a === void 0 ? void 0 : _a.bind) === null || _b === void 0 ? void 0 : _b.call(_a, window) : undefined, | ||
| fetchInterceptor: fetchInterceptor, | ||
| serialize: function (request) { | ||
| return __assign(__assign({}, request), { data: mapItems(request.data, function (obj) { return (obj instanceof PureModel ? modelToJSON(obj) : obj); }) || | ||
| undefined }); | ||
| }, | ||
| Response: Response, | ||
| }; | ||
| } | ||
| var HttpMethod; | ||
| (function (HttpMethod) { | ||
| HttpMethod["Get"] = "GET"; | ||
| HttpMethod["Post"] = "POST"; | ||
| HttpMethod["Put"] = "PUT"; | ||
| HttpMethod["Patch"] = "Patch"; | ||
| HttpMethod["Delete"] = "Delete"; | ||
| HttpMethod["Options"] = "Options"; | ||
| HttpMethod["Head"] = "Head"; | ||
| })(HttpMethod || (HttpMethod = {})); | ||
| // Based on service worker strategies https://developers.google.com/web/tools/workbox/modules/workbox-strategies | ||
| var CachingStrategy; | ||
| (function (CachingStrategy) { | ||
| CachingStrategy[CachingStrategy["NetworkOnly"] = 1] = "NetworkOnly"; | ||
| CachingStrategy[CachingStrategy["NetworkFirst"] = 2] = "NetworkFirst"; | ||
| CachingStrategy[CachingStrategy["StaleWhileRevalidate"] = 3] = "StaleWhileRevalidate"; | ||
| CachingStrategy[CachingStrategy["CacheOnly"] = 4] = "CacheOnly"; | ||
| CachingStrategy[CachingStrategy["CacheFirst"] = 5] = "CacheFirst"; | ||
| CachingStrategy[CachingStrategy["StaleAndUpdate"] = 6] = "StaleAndUpdate"; | ||
| })(CachingStrategy || (CachingStrategy = {})); | ||
| var cacheStorage = []; | ||
| function saveCache(url, response) { | ||
| if (response && response.isSuccess && (response.data || response.data === null)) { | ||
| var types = mapItems(response.data || [], getModelType); | ||
| cacheStorage = cacheStorage.filter(function (item) { return item.url !== url; }); | ||
| cacheStorage.unshift({ | ||
| response: response.snapshot, | ||
| collection: response.collection, | ||
| time: Date.now(), | ||
| types: [].concat(types), | ||
| url: url, | ||
| }); | ||
| } | ||
| } | ||
| function getCache(url, maxAge) { | ||
| var ageLimit = Date.now() - maxAge * 1000; | ||
| var cache = cacheStorage.find(function (item) { return item.url === url && item.time > ageLimit; }); | ||
| if (cache) { | ||
| var data = cache.response; | ||
| return { | ||
| // @ts-ignore Array headers that are supported but shouldn't be exposed in types | ||
| response: new Response(data.response, cache.collection, data.options), | ||
| time: cache.time, | ||
| types: cache.types, | ||
| url: cache.url, | ||
| }; | ||
| } | ||
| return undefined; | ||
| } | ||
| function clearAllCache() { | ||
| cacheStorage.length = 0; | ||
| } | ||
| function clearCacheByType(type) { | ||
| cacheStorage = cacheStorage.filter(function (item) { return !item.types.includes(type); }); | ||
| } | ||
| function getCacheByCollection(collection) { | ||
| return cacheStorage | ||
| .filter(function (item) { return item.collection === collection; }) | ||
| .map(function (item) { return Object.assign({}, item, { collection: undefined }); }); | ||
| } | ||
| function saveCacheForCollection(cacheItems, collection) { | ||
| cacheStorage.push.apply(cacheStorage, __spreadArray(__spreadArray([], cacheStorage, false), cacheItems.map(function (item) { return Object.assign({ collection: collection }, item); }), false)); | ||
| } | ||
| function makeNetworkCall(params, next, doCacheResponse, existingResponse) { | ||
| if (doCacheResponse === void 0) { doCacheResponse = false; } | ||
| return next(params).then(function (response) { | ||
| var finalResponse = response; | ||
| if (existingResponse) { | ||
| finalResponse = existingResponse.update(response, params.views); | ||
| } | ||
| if (doCacheResponse) { | ||
| saveCache(params.url, finalResponse); | ||
| } | ||
| return finalResponse; | ||
| }, function (response) { | ||
| throw response; | ||
| }); | ||
| } | ||
| function getLocalNetworkError(message, reqOptions, collection) { | ||
| var _a, _b; | ||
| return new Response({ | ||
| error: new Error(message), | ||
| collection: collection, | ||
| requestHeaders: (_b = (_a = reqOptions.options) === null || _a === void 0 ? void 0 : _a.networkConfig) === null || _b === void 0 ? void 0 : _b.headers, | ||
| }, collection); | ||
| } | ||
| function cacheInterceptor(cache, maxCacheAge) { | ||
| if (maxCacheAge === void 0) { maxCacheAge = Infinity; } | ||
| return function (request, next) { | ||
| var _a, _b, _c, _d, _e; | ||
| if (!next) { | ||
| throw new Error("Cache interceptor can't be the last interceptor"); | ||
| } | ||
| var isCacheSupported = request.method.toUpperCase() === HttpMethod.Get; | ||
| var cacheStrategy = ((_b = (_a = request.options) === null || _a === void 0 ? void 0 : _a.cacheOptions) === null || _b === void 0 ? void 0 : _b.skipCache) || !isCacheSupported | ||
| ? CachingStrategy.NetworkOnly | ||
| : ((_d = (_c = request.options) === null || _c === void 0 ? void 0 : _c.cacheOptions) === null || _d === void 0 ? void 0 : _d.cachingStrategy) || cache; | ||
| // NetworkOnly - Ignore cache | ||
| if (cacheStrategy === CachingStrategy.NetworkOnly) { | ||
| return makeNetworkCall(request, next); | ||
| } | ||
| var cacheContent = getCache(request.url, maxCacheAge); | ||
| // NetworkFirst - Fallback to cache only on network error | ||
| if (cacheStrategy === CachingStrategy.NetworkFirst) { | ||
| return makeNetworkCall(request, next, true).catch(function (errorResponse) { | ||
| if (cacheContent) { | ||
| return cacheContent.response; | ||
| } | ||
| throw errorResponse; | ||
| }); | ||
| } | ||
| // StaleWhileRevalidate - Use cache and update it in background | ||
| if (cacheStrategy === CachingStrategy.StaleWhileRevalidate) { | ||
| var network = makeNetworkCall(request, next, true); | ||
| if (cacheContent) { | ||
| network.catch(function () { | ||
| // Ignore the failure | ||
| }); | ||
| return Promise.resolve(cacheContent.response); | ||
| } | ||
| return network; | ||
| } | ||
| // CacheOnly - Fail if nothing in cache | ||
| if (cacheStrategy === CachingStrategy.CacheOnly) { | ||
| if (cacheContent) { | ||
| return Promise.resolve(cacheContent.response); | ||
| } | ||
| return Promise.reject(getLocalNetworkError('No cache for this request', request, request === null || request === void 0 ? void 0 : request.collection)); | ||
| } | ||
| // CacheFirst - Use cache if available | ||
| if (cacheStrategy === CachingStrategy.CacheFirst) { | ||
| return cacheContent | ||
| ? Promise.resolve(cacheContent.response) | ||
| : makeNetworkCall(request, next, true); | ||
| } | ||
| // StaleAndUpdate - Use cache and update response once network is complete | ||
| if (cacheStrategy === CachingStrategy.StaleAndUpdate) { | ||
| var existingResponse = (_e = cacheContent === null || cacheContent === void 0 ? void 0 : cacheContent.response) === null || _e === void 0 ? void 0 : _e.clone(); | ||
| var network = makeNetworkCall(request, next, true, existingResponse); | ||
| if (existingResponse) { | ||
| network.catch(function () { | ||
| // Ignore the failure | ||
| }); | ||
| return Promise.resolve(existingResponse); | ||
| } | ||
| return network; | ||
| } | ||
| return Promise.reject(getLocalNetworkError('Invalid caching strategy', request, request === null || request === void 0 ? void 0 : request.collection)); | ||
| }; | ||
| } | ||
| var BodyType; | ||
| (function (BodyType) { | ||
| BodyType[BodyType["Raw"] = 0] = "Raw"; | ||
| BodyType[BodyType["Json"] = 1] = "Json"; | ||
| BodyType[BodyType["Multipart"] = 2] = "Multipart"; | ||
| BodyType[BodyType["Urlencoded"] = 3] = "Urlencoded"; | ||
| })(BodyType || (BodyType = {})); | ||
| function setUrl(url, type) { | ||
| if (type === void 0) { type = PureModel; } | ||
| return function (pipeline) { | ||
| pipeline['_options'].url = url; | ||
| pipeline['_config'].type = type; | ||
| }; | ||
| } | ||
| function addInterceptor(fn, name) { | ||
| if (name === void 0) { name = fn.name; } | ||
| return function (pipeline) { | ||
| pipeline.interceptors = pipeline.interceptors.filter(function (interceptor) { return interceptor.name !== name; }); | ||
| pipeline.interceptors.push({ name: name, fn: fn }); | ||
| }; | ||
| } | ||
| function upsertInterceptor(fn, name) { | ||
| if (name === void 0) { name = fn.name; } | ||
| return function (pipeline) { | ||
| var interceptor = pipeline.interceptors.find(function (interceptor) { return interceptor.name === name; }); | ||
| if (interceptor) { | ||
| interceptor.fn = fn; | ||
| } | ||
| else { | ||
| pipeline.interceptors.push({ name: name, fn: fn }); | ||
| } | ||
| }; | ||
| } | ||
| function cache(strategy, maxAge) { | ||
| if (maxAge === void 0) { maxAge = Infinity; } | ||
| return upsertInterceptor(cacheInterceptor(strategy, maxAge), 'cache'); | ||
| } | ||
| function method(method) { | ||
| return function (pipeline) { | ||
| pipeline['_options'].method = method; | ||
| }; | ||
| } | ||
| function body(body, bodyType) { | ||
| return function (pipeline) { | ||
| if (bodyType || bodyType === 0) { | ||
| pipeline['_options'].bodyType = bodyType; | ||
| } | ||
| else if (body instanceof FormData) { | ||
| pipeline['_options'].bodyType = BodyType.Multipart; | ||
| } | ||
| else if (typeof body === 'object') { | ||
| pipeline['_options'].bodyType = BodyType.Json; | ||
| } | ||
| else { | ||
| pipeline['_options'].bodyType = BodyType.Raw; | ||
| } | ||
| pipeline['_options'].body = body; | ||
| }; | ||
| } | ||
| function query(name, value) { | ||
| return function (pipeline) { | ||
| if (typeof name === 'string') { | ||
| pipeline['_options'].query[name] = value; | ||
| } | ||
| else { | ||
| Object.assign(pipeline['_options'].query, name); | ||
| } | ||
| }; | ||
| } | ||
| function header(name, value) { | ||
| return function (pipeline) { | ||
| if (typeof name === 'string') { | ||
| pipeline['_options'].headers[name] = value || ''; | ||
| } | ||
| else { | ||
| Object.assign(pipeline['_options'].headers, name); | ||
| } | ||
| }; | ||
| } | ||
| function params(name, value) { | ||
| return function (pipeline) { | ||
| if (typeof name === 'string') { | ||
| pipeline['_options'].params[name] = value; | ||
| } | ||
| else { | ||
| Object.assign(pipeline['_options'].params, name); | ||
| } | ||
| }; | ||
| } | ||
| function encodeQueryString(encodeQueryString) { | ||
| return function (pipeline) { | ||
| pipeline['_config'].encodeQueryString = encodeQueryString; | ||
| }; | ||
| } | ||
| function paramArrayType(paramArrayType) { | ||
| return function (pipeline) { | ||
| pipeline['_config'].paramArrayType = paramArrayType; | ||
| }; | ||
| } | ||
| function fetchReference(fetchReference) { | ||
| return function (pipeline) { | ||
| var config = pipeline['_config']; | ||
| config.fetchReference = fetchReference; | ||
| upsertInterceptor(config.fetchInterceptor(config.fetchReference, config.serialize, config.parse, config.Response), 'fetch')(pipeline); | ||
| }; | ||
| } | ||
| function serializer(serialize) { | ||
| return function (pipeline) { | ||
| var config = pipeline['_config']; | ||
| config.serialize = serialize; | ||
| upsertInterceptor(config.fetchInterceptor(config.fetchReference, config.serialize, config.parse, config.Response), 'fetch')(pipeline); | ||
| }; | ||
| } | ||
| function parser(parse) { | ||
| return function (pipeline) { | ||
| var config = pipeline['_config']; | ||
| config.parse = parse; | ||
| upsertInterceptor(config.fetchInterceptor(config.fetchReference, config.serialize, config.parse, config.Response), 'fetch')(pipeline); | ||
| }; | ||
| } | ||
| function collection(collection) { | ||
| return function (pipeline) { | ||
| pipeline['_config'].collection = collection; | ||
| }; | ||
| } | ||
| function requestOptions(options) { | ||
| return function (pipeline) { | ||
| var _a, _b, _c, _d, _e; | ||
| if (options === null || options === void 0 ? void 0 : options.query) { | ||
| query(options === null || options === void 0 ? void 0 : options.query)(pipeline); | ||
| } | ||
| if ((_a = options === null || options === void 0 ? void 0 : options.networkConfig) === null || _a === void 0 ? void 0 : _a.headers) { | ||
| header((_b = options === null || options === void 0 ? void 0 : options.networkConfig) === null || _b === void 0 ? void 0 : _b.headers)(pipeline); | ||
| } | ||
| if ((_c = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cachingStrategy) { | ||
| cache((_d = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _d === void 0 ? void 0 : _d.cachingStrategy, (_e = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _e === void 0 ? void 0 : _e.maxAge)(pipeline); | ||
| } | ||
| }; | ||
| } | ||
| var BaseRequest = /** @class */ (function () { | ||
| function BaseRequest(baseUrl) { | ||
| this._config = getDefaultConfig(); | ||
| this._options = { | ||
| method: HttpMethod.Get, | ||
| headers: {}, | ||
| query: {}, | ||
| params: {}, | ||
| bodyType: BodyType.Json, | ||
| }; | ||
| this.interceptors = [ | ||
| { | ||
| fn: fetchInterceptor(this._config.fetchReference, this._config.serialize, this._config.parse), | ||
| name: 'fetch', | ||
| }, | ||
| { | ||
| fn: cacheInterceptor(isBrowser ? CachingStrategy.CacheFirst : CachingStrategy.NetworkOnly), | ||
| name: 'cache', | ||
| }, | ||
| ]; | ||
| this._config.baseUrl = baseUrl; | ||
| } | ||
| BaseRequest.prototype.pipe = function () { | ||
| var operators = []; | ||
| for (var _i = 0; _i < arguments.length; _i++) { | ||
| operators[_i] = arguments[_i]; | ||
| } | ||
| var destinationPipeline = this.clone(); | ||
| operators | ||
| .filter(Boolean) | ||
| .forEach(function (operator) { return operator(destinationPipeline); }); | ||
| return destinationPipeline; | ||
| }; | ||
| BaseRequest.prototype.processBody = function () { | ||
| if (!this._options.body) { | ||
| return; | ||
| } | ||
| if (this._options.bodyType === BodyType.Json) { | ||
| this._options.headers['content-type'] = | ||
| this._options.headers['content-type'] || 'application/json'; | ||
| return this._options.body; | ||
| } | ||
| else if (this._options.bodyType === BodyType.Urlencoded) { | ||
| this._options.headers['content-type'] = | ||
| this._options.headers['content-type'] || 'application/x-www-form-urlencoded'; | ||
| return typeof this._options.body === 'string' | ||
| ? this._options.body | ||
| : appendQueryParams('', this._options.body, this._config.paramArrayType, this._config.encodeQueryString).slice(1); | ||
| } | ||
| else if (this._options.bodyType === BodyType.Multipart) { | ||
| this._options.headers['content-type'] = | ||
| this._options.headers['content-type'] || 'multipart/form-data'; | ||
| return this._options.body instanceof FormData | ||
| ? this._options.body | ||
| : new FormData(this._options.body); | ||
| } | ||
| else { | ||
| return this._options.body; | ||
| } | ||
| }; | ||
| BaseRequest.prototype.fetch = function (params, queryParams, body$1, bodyType) { | ||
| var request = body$1 === undefined ? this : this.pipe(body(body$1, bodyType)); | ||
| if (!request._options.url) { | ||
| throw new Error('URL should be defined'); | ||
| } | ||
| var urlParams = Object.assign({}, request._options.params, params || {}); | ||
| var url = interpolateParams("".concat(request._config.baseUrl).concat(request._options.url), urlParams); | ||
| var processedUrl = appendQueryParams(url, Object.assign({}, request._options.query, queryParams), request._config.paramArrayType, request._config.encodeQueryString); | ||
| var requestRef = { | ||
| url: processedUrl, | ||
| method: request._options.method, | ||
| data: request.processBody(), | ||
| collection: request._config.collection, | ||
| params: params, | ||
| options: { | ||
| networkConfig: { | ||
| headers: request._options.headers, | ||
| }, | ||
| }, | ||
| views: request._config.views, | ||
| type: request._config.type, | ||
| }; | ||
| var interceptorChain = request.interceptors.reduce(function (next, interceptor) { | ||
| return function (options) { return interceptor.fn(options, next); }; | ||
| }, undefined); | ||
| if (!interceptorChain) { | ||
| throw new Error('Something went wrong'); | ||
| } | ||
| return interceptorChain(requestRef); | ||
| }; | ||
| BaseRequest.prototype.clone = function (BaseRequestConstructor) { | ||
| if (BaseRequestConstructor === void 0) { BaseRequestConstructor = this.constructor; } | ||
| // Can't use `new BaseRequest`, because we would lose the overridden methods | ||
| var clone = new BaseRequestConstructor(this._config.baseUrl); | ||
| clone.interceptors = deepCopy(this.interceptors); | ||
| clone._config = deepCopy(this._config); | ||
| clone._options = deepCopy(this._options); | ||
| // Manually copy complex objects | ||
| clone._config.collection = this._config.collection; | ||
| clone._config.fetchInterceptor = this._config.fetchInterceptor; | ||
| clone._config.fetchReference = this._config.fetchReference; | ||
| clone._config.Response = this._config.Response; | ||
| clone._config.type = this._config.type; | ||
| return clone; | ||
| }; | ||
| return BaseRequest; | ||
| }()); | ||
| function addOptionsToRequest(request, options) { | ||
| return request.pipe(requestOptions(options)); | ||
| } | ||
| function decorateCollection(BaseClass) { | ||
| var NetworkCollection = /** @class */ (function (_super) { | ||
| __extends(NetworkCollection, _super); | ||
| function NetworkCollection(data) { | ||
| if (data === void 0) { data = []; } | ||
| var _this = _super.call(this, data) || this; | ||
| if (!(data instanceof Array) && (data === null || data === void 0 ? void 0 : data.cache)) { | ||
| saveCacheForCollection(data.cache, _this); | ||
| } | ||
| return _this; | ||
| } | ||
| NetworkCollection.prototype.getConstructor = function (type) { | ||
| var Collection = this.constructor; | ||
| var modelType = getModelType(type); | ||
| return ( | ||
| // @ts-ignore | ||
| Collection.types.find(function (item) { return getModelType(item) === modelType; }) || Collection.defaultModel); | ||
| }; | ||
| NetworkCollection.prototype.getOne = function (type, id, options) { | ||
| var root = this.getConstructor(type); | ||
| if (!root || !root.network) { | ||
| throw new Error('The network configuration is wrong for the given model'); | ||
| } | ||
| if (root.network instanceof BaseRequest) { | ||
| return root.network | ||
| .pipe(requestOptions(options), setUrl("".concat(root.network['_options'].url, "/{id}"), root)) | ||
| .fetch({ | ||
| id: id, | ||
| }); | ||
| } | ||
| if (!root.network.getOne) { | ||
| throw new Error('The getOne network request was not defined on the given model'); | ||
| } | ||
| return addOptionsToRequest(root.network.getOne, options).fetch({ | ||
| id: id, | ||
| }); | ||
| }; | ||
| NetworkCollection.prototype.getMany = function (type, options) { | ||
| var root = this.getConstructor(type); | ||
| if (!root || !root.network) { | ||
| throw new Error('The network configuration is wrong for the given model'); | ||
| } | ||
| if (root.network instanceof BaseRequest) { | ||
| return addOptionsToRequest(root.network, options).fetch(); | ||
| } | ||
| if (!root.network.getMany) { | ||
| throw new Error('The getMany network request was not defined on the given model'); | ||
| } | ||
| return addOptionsToRequest(root.network.getMany, options).fetch(); | ||
| }; | ||
| NetworkCollection.prototype.removeOne = function (type, id, options) { | ||
| var _this = this; | ||
| var realType = getModelType(type); | ||
| var realId = typeof id !== 'object' && typeof id !== 'undefined' && typeof id !== 'boolean' ? id : null; | ||
| var realOptions = (realId !== null | ||
| ? options | ||
| : id); | ||
| var model = realId ? this.findOne(realType, realId) : realType; | ||
| if (!model) { | ||
| throw new Error('The model was not found'); | ||
| } | ||
| if (realOptions === false || realOptions === undefined) { | ||
| return Promise.resolve(_super.prototype.removeOne.call(this, model)); | ||
| } | ||
| clearCacheByType(getModelType(type)); | ||
| return model | ||
| .destroy(typeof realOptions === 'object' ? realOptions : {}) | ||
| .then(function () { | ||
| _super.prototype.removeOne.call(_this, model); | ||
| }); | ||
| }; | ||
| NetworkCollection.prototype.toJSON = function () { | ||
| return Object.assign({}, _super.prototype.toJSON.call(this), { | ||
| cache: getCacheByCollection(this), | ||
| }); | ||
| }; | ||
| return NetworkCollection; | ||
| }(BaseClass)); | ||
| return NetworkCollection; | ||
| } | ||
| var NETWORK_PERSISTED = 'networkPersisted'; | ||
| function handleResponse(record) { | ||
| return function (response) { | ||
| if (response.error) { | ||
| throw response.error; | ||
| } | ||
| if (response.status === 204) { | ||
| setMeta(record, NETWORK_PERSISTED, true); | ||
| return record; | ||
| } | ||
| setMeta(record, NETWORK_PERSISTED, true); | ||
| var data = response.replaceData(record).data || record; | ||
| commitModel(data); | ||
| return data; | ||
| }; | ||
| } | ||
| function saveModel(model, options) { | ||
| var _a, _b, _c, _d, _e; | ||
| var ModelConstructor = model.constructor; | ||
| if (!ModelConstructor.network) { | ||
| throw new Error('The network property needs to be defined on the model'); | ||
| } | ||
| var isPersisted = getMeta(model, NETWORK_PERSISTED, false); | ||
| var baseRequest; | ||
| if (ModelConstructor.network instanceof BaseRequest) { | ||
| baseRequest = isPersisted | ||
| ? ModelConstructor.network.pipe(method(HttpMethod.Put), setUrl("".concat(ModelConstructor.network['_options'].url, "/{id}"), ModelConstructor)) | ||
| : ModelConstructor.network.pipe(method(HttpMethod.Post)); | ||
| } | ||
| else { | ||
| baseRequest = isPersisted ? ModelConstructor.network.update : ModelConstructor.network.create; | ||
| } | ||
| if (!baseRequest) { | ||
| throw new Error('The base request has not been defined'); | ||
| } | ||
| var request = baseRequest.pipe((options === null || options === void 0 ? void 0 : options.query) && query(options === null || options === void 0 ? void 0 : options.query), ((_a = options === null || options === void 0 ? void 0 : options.networkConfig) === null || _a === void 0 ? void 0 : _a.headers) && header((_b = options === null || options === void 0 ? void 0 : options.networkConfig) === null || _b === void 0 ? void 0 : _b.headers), ((_c = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cachingStrategy) && | ||
| cache((_d = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _d === void 0 ? void 0 : _d.cachingStrategy, (_e = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _e === void 0 ? void 0 : _e.maxAge), body(model)); | ||
| return request.fetch({ id: getModelId(model) }).then(handleResponse(model)); | ||
| } | ||
| function removeModel(model, options) { | ||
| var _a, _b, _c, _d, _e; | ||
| var ModelConstructor = model.constructor; | ||
| if (!ModelConstructor.network) { | ||
| throw new Error('The network property needs to be defined on the model'); | ||
| } | ||
| var isPersisted = getMeta(model, NETWORK_PERSISTED, false); | ||
| var baseRequest; | ||
| if (ModelConstructor.network instanceof BaseRequest) { | ||
| baseRequest = isPersisted | ||
| ? ModelConstructor.network.pipe(method(HttpMethod.Delete), setUrl("".concat(ModelConstructor.network['_options'].url, "/{id}"), ModelConstructor)) | ||
| : false; | ||
| } | ||
| else { | ||
| baseRequest = isPersisted ? ModelConstructor.network.destroy : false; | ||
| } | ||
| if (!baseRequest && baseRequest !== false) { | ||
| throw new Error('The base request has not been defined'); | ||
| } | ||
| if (baseRequest) { | ||
| baseRequest | ||
| .pipe((options === null || options === void 0 ? void 0 : options.query) && query(options === null || options === void 0 ? void 0 : options.query), ((_a = options === null || options === void 0 ? void 0 : options.networkConfig) === null || _a === void 0 ? void 0 : _a.headers) && header((_b = options === null || options === void 0 ? void 0 : options.networkConfig) === null || _b === void 0 ? void 0 : _b.headers), ((_c = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cachingStrategy) && | ||
| cache((_d = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _d === void 0 ? void 0 : _d.cachingStrategy, (_e = options === null || options === void 0 ? void 0 : options.cacheOptions) === null || _e === void 0 ? void 0 : _e.maxAge)) | ||
| .fetch({ id: getModelId(model) }) | ||
| .then(function () { | ||
| var collection = getModelCollection(model); | ||
| if (collection) { | ||
| collection.removeOne(model); | ||
| } | ||
| }); | ||
| } | ||
| return Promise.resolve(); | ||
| } | ||
| var HYDRATIZATION_KEYS = [NETWORK_PERSISTED]; | ||
| function decorateModel(BaseClass) { | ||
| var NetworkModel = /** @class */ (function (_super) { | ||
| __extends(NetworkModel, _super); | ||
| function NetworkModel(data, collection) { | ||
| if (data === void 0) { data = {}; } | ||
| var _this = _super.call(this, data, collection) || this; | ||
| var modelMeta = (data === null || data === void 0 ? void 0 : data[META_FIELD]) || {}; | ||
| HYDRATIZATION_KEYS.forEach(function (key) { | ||
| if (key in modelMeta) { | ||
| setMeta(_this, key, modelMeta[key]); | ||
| } | ||
| }); | ||
| return _this; | ||
| } | ||
| NetworkModel.prototype.save = function (options) { | ||
| return saveModel(this, options); | ||
| }; | ||
| NetworkModel.prototype.destroy = function (options) { | ||
| return removeModel(this, options); | ||
| }; | ||
| return NetworkModel; | ||
| }(BaseClass)); | ||
| return NetworkModel; | ||
| } | ||
| function withNetwork(Base) { | ||
| if (isModel(Base)) { | ||
| // @ts-ignore | ||
| return decorateModel(Base); | ||
| } | ||
| if (isCollection(Base)) { | ||
| // @ts-ignore | ||
| return decorateCollection(Base); | ||
| } | ||
| // if (isView(Base)) { | ||
| // // @ts-ignore | ||
| // return decorateView<T>(Base); | ||
| // } | ||
| throw new Error('The instance needs to be a model, collection or a view'); | ||
| } | ||
| export { BaseRequest, CachingStrategy, HttpMethod, ParamArrayType, Response, addInterceptor, body, cache, clearAllCache, clearCacheByType, collection, encodeQueryString, fetchReference, header, method, paramArrayType, params, parser, query, requestOptions, serializer, setUrl, upsertInterceptor, withNetwork }; |
| import { IType, PureModel, PureCollection } from '@datx/core'; | ||
| import { Response } from '../Response'; | ||
| import { IResponseSnapshot } from '../interfaces/IResponseSnapshot'; | ||
| import { CachingStrategy } from '../enums/CachingStrategy'; | ||
| import { IFetchOptions } from '../interfaces/IFetchOptions'; | ||
| import { INetworkHandler } from '../interfaces/INetworkHandler'; | ||
| export interface ICache { | ||
| response: Response<PureModel>; | ||
| time: number; | ||
| types: Array<IType>; | ||
| url: string; | ||
| } | ||
| export interface ICacheInternal { | ||
| response: IResponseSnapshot; | ||
| collection?: PureCollection; | ||
| time: number; | ||
| types: Array<IType>; | ||
| url: string; | ||
| } | ||
| export declare function saveCache(url: string, response: Response<PureModel>): void; | ||
| export declare function getCache(url: string, maxAge: number): ICache | undefined; | ||
| export declare function clearAllCache(): void; | ||
| export declare function clearCacheByType(type: IType): void; | ||
| export declare function getCacheByCollection(collection?: PureCollection): Array<Omit<ICacheInternal, 'collection'>>; | ||
| export declare function saveCacheForCollection(cacheItems: Array<Omit<ICacheInternal, 'collection'>>, collection?: PureCollection): void; | ||
| export declare function cacheInterceptor<T extends PureModel>(cache: CachingStrategy, maxCacheAge?: number): (request: IFetchOptions, next?: INetworkHandler<PureModel> | undefined) => Promise<Response<T>>; |
| import { PureModel } from '@datx/core'; | ||
| import { IFetchOptions } from '../interfaces/IFetchOptions'; | ||
| import { INetworkHandler } from '../interfaces/INetworkHandler'; | ||
| import { IResponseObject } from '../interfaces/IResponseObject'; | ||
| import { Response as ResponseClass } from '../Response'; | ||
| export declare function fetchInterceptor<T extends PureModel>(fetchReference?: typeof fetch, serialize?: (options: IFetchOptions) => IFetchOptions, parse?: (data: object, options: IResponseObject) => object, Response?: typeof ResponseClass): (request: IFetchOptions, _next?: INetworkHandler<PureModel> | undefined) => Promise<ResponseClass<T>>; |
| import { IHeaders } from './IHeaders'; | ||
| export declare type FetchType = (method: string, url: string, body?: object, requestHeaders?: IHeaders) => Promise<object>; |
| import { PureCollection, IType, PureModel, View } from '@datx/core'; | ||
| import { ParamArrayType } from '../enums/ParamArrayType'; | ||
| import { IFetchOptions } from './IFetchOptions'; | ||
| import { IResponseObject } from './IResponseObject'; | ||
| import { fetchInterceptor } from '../interceptors/fetch'; | ||
| import { Response } from '../Response'; | ||
| export interface IConfigType { | ||
| baseUrl: string; | ||
| paramArrayType: ParamArrayType; | ||
| encodeQueryString: boolean; | ||
| collection?: PureCollection; | ||
| type?: IType | typeof PureModel; | ||
| views?: Array<View>; | ||
| fetchReference?: typeof fetch; | ||
| serialize?: (options: IFetchOptions) => IFetchOptions; | ||
| parse?: (data: object, options: IResponseObject) => object; | ||
| fetchInterceptor: typeof fetchInterceptor; | ||
| Response: typeof Response; | ||
| } |
| import { View, PureCollection, IType, PureModel } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { HttpMethod } from '../enums/HttpMethod'; | ||
| export interface IFetchOptions { | ||
| url: string; | ||
| options?: IRequestOptions; | ||
| params?: object | null; | ||
| data?: string | object | FormData; | ||
| method: HttpMethod; | ||
| collection?: PureCollection; | ||
| skipCache?: boolean; | ||
| views?: Array<View>; | ||
| type?: IType | typeof PureModel; | ||
| } |
| export declare type IHeaders = Record<string, string>; |
| import { IFetchOptions } from './IFetchOptions'; | ||
| import { Response } from '../Response'; | ||
| import { INetworkHandler } from './INetworkHandler'; | ||
| import { PureModel } from '@datx/core'; | ||
| export declare type IInterceptor<T extends PureModel = PureModel> = (request: IFetchOptions, next?: INetworkHandler) => Promise<Response<T>>; |
| import { BaseRequest } from '../BaseRequest'; | ||
| export declare type IModelNetworkConfig = BaseRequest | { | ||
| getMany?: BaseRequest; | ||
| getOne?: BaseRequest; | ||
| create?: BaseRequest; | ||
| update?: BaseRequest; | ||
| destroy?: BaseRequest; | ||
| }; |
| import { PureModel, PureCollection, IType } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { Response } from '../Response'; | ||
| import { INetworkModel } from './INetworkModel'; | ||
| import { INetworkModelConstructor } from './INetworkModelConstructor'; | ||
| export interface INetworkCollection extends PureCollection { | ||
| getOne<T extends INetworkModel = INetworkModel>(type: IType | INetworkModelConstructor, id: string, options?: IRequestOptions): Promise<Response<T>>; | ||
| getMany<T extends INetworkModel = INetworkModel>(type: IType | INetworkModelConstructor, options?: IRequestOptions): Promise<Response<T>>; | ||
| removeOne(type: IType | typeof PureModel, id: string, options?: boolean | IRequestOptions): Promise<void>; | ||
| removeOne(model: INetworkModel, options?: boolean | IRequestOptions): Promise<void>; | ||
| } |
| import { PureCollection, IRawModel, IRawCollection } from '@datx/core'; | ||
| import { INetworkCollection } from './INetworkCollection'; | ||
| export interface INetworkCollectionConstructor extends PureCollection { | ||
| new (data?: Array<IRawModel> | IRawCollection): INetworkCollection; | ||
| } |
| import { IFetchOptions } from './IFetchOptions'; | ||
| import { PureModel } from '@datx/core'; | ||
| import { Response } from '../Response'; | ||
| export declare type INetworkHandler<T extends PureModel = PureModel> = (request: IFetchOptions) => Promise<Response<T>>; |
| import { PureModel } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| export interface INetworkModel extends PureModel { | ||
| save(options?: IRequestOptions): Promise<INetworkModel>; | ||
| destroy(options?: IRequestOptions): Promise<void>; | ||
| } |
| import { INetworkModel } from './INetworkModel'; | ||
| import { IModelNetworkConfig } from './IModelNetworkConfig'; | ||
| import { IModelConstructor } from '@datx/core'; | ||
| export interface INetworkModelConstructor extends IModelConstructor { | ||
| network?: IModelNetworkConfig; | ||
| new (): INetworkModel; | ||
| } |
| import { View } from '@datx/core'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { Response } from '../Response'; | ||
| import { INetworkModel } from './INetworkModel'; | ||
| export interface INetworkView<T extends INetworkModel = INetworkModel> extends View<T> { | ||
| sync(body?: Response<T>): T | Array<T> | null; | ||
| getOne(id: string, options?: IRequestOptions): Promise<Response<T>>; | ||
| getMany(options?: IRequestOptions): Promise<Response<T>>; | ||
| } |
| import { BaseRequest } from '../BaseRequest'; | ||
| export declare type IPipeOperator = (request: BaseRequest) => void; |
| import { IHeaders } from './IHeaders'; | ||
| import { CachingStrategy } from '../enums/CachingStrategy'; | ||
| export interface IRequestOptions { | ||
| query?: Record<string, string | Array<string> | object>; | ||
| cacheOptions?: { | ||
| cachingStrategy?: CachingStrategy; | ||
| maxAge?: number; | ||
| skipCache?: boolean; | ||
| }; | ||
| networkConfig?: { | ||
| headers?: IHeaders; | ||
| }; | ||
| } |
| import { View } from '@datx/core'; | ||
| import { IResponseHeaders } from '@datx/utils'; | ||
| import { IHeaders } from './IHeaders'; | ||
| import { IRequestOptions } from './IRequestOptions'; | ||
| import { IResponseObject } from './IResponseObject'; | ||
| export interface IResponseInternal { | ||
| headers?: IResponseHeaders; | ||
| requestHeaders?: IHeaders; | ||
| error?: Array<string | object> | Error; | ||
| status?: number; | ||
| options?: IRequestOptions; | ||
| response: IResponseObject; | ||
| views: Array<View>; | ||
| } |
| import { PureCollection, IType, PureModel } from '@datx/core'; | ||
| import { IResponseHeaders } from '@datx/utils'; | ||
| import { IHeaders } from './IHeaders'; | ||
| export interface IResponseObject { | ||
| data?: object; | ||
| error?: Error; | ||
| headers?: IResponseHeaders; | ||
| requestHeaders?: IHeaders; | ||
| status?: number; | ||
| collection?: PureCollection; | ||
| type?: IType | typeof PureModel; | ||
| } |
| import { IRequestOptions } from './IRequestOptions'; | ||
| export interface IResponseSnapshot { | ||
| response: Omit<object, 'headers'> & { | ||
| headers?: Array<[string, string]>; | ||
| }; | ||
| options?: IRequestOptions; | ||
| } |
| import { BaseRequest } from './BaseRequest'; | ||
| import { IInterceptor } from './interfaces/IInterceptor'; | ||
| import { CachingStrategy } from './enums/CachingStrategy'; | ||
| import { HttpMethod } from './enums/HttpMethod'; | ||
| import { BodyType } from './enums/BodyType'; | ||
| import { ParamArrayType } from './enums/ParamArrayType'; | ||
| import { PureCollection, IType, PureModel } from '@datx/core'; | ||
| import { IResponseObject } from './interfaces/IResponseObject'; | ||
| import { IFetchOptions } from './interfaces/IFetchOptions'; | ||
| import { IRequestOptions } from './interfaces/IRequestOptions'; | ||
| export declare function setUrl(url: string, type?: IType | typeof PureModel): (pipeline: BaseRequest) => void; | ||
| export declare function addInterceptor(fn: IInterceptor, name?: string): (pipeline: BaseRequest) => void; | ||
| export declare function upsertInterceptor(fn: IInterceptor, name?: string): (pipeline: BaseRequest) => void; | ||
| export declare function removeInterceptor(name: string): (pipeline: BaseRequest) => void; | ||
| export declare function cache(strategy: CachingStrategy, maxAge?: number): (pipeline: BaseRequest) => void; | ||
| export declare function method(method: HttpMethod): (pipeline: BaseRequest) => void; | ||
| export declare function body(body: unknown, bodyType?: BodyType): (pipeline: BaseRequest) => void; | ||
| export declare function query(name: string, value: string | Array<string> | object | undefined): (pipeline: BaseRequest) => void; | ||
| export declare function query(params: Record<string, string | Array<string> | object | undefined>): (pipeline: BaseRequest) => void; | ||
| export declare function header(name: string, value: string): (pipeline: BaseRequest) => void; | ||
| export declare function header(params: Record<string, string>): (pipeline: BaseRequest) => void; | ||
| export declare function params(name: string, value: string): (pipeline: BaseRequest) => void; | ||
| export declare function params(params: Record<string, string>): (pipeline: BaseRequest) => void; | ||
| export declare function encodeQueryString(encodeQueryString: boolean): (pipeline: BaseRequest) => void; | ||
| export declare function paramArrayType(paramArrayType: ParamArrayType): (pipeline: BaseRequest) => void; | ||
| export declare function fetchReference(fetchReference: typeof fetch): (pipeline: BaseRequest) => void; | ||
| export declare function serializer(serialize: (request: IFetchOptions) => IFetchOptions): (pipeline: BaseRequest) => void; | ||
| export declare function parser(parse: (data: object, response: IResponseObject) => object): (pipeline: BaseRequest) => void; | ||
| export declare function collection(collection?: PureCollection): (pipeline: BaseRequest) => void; | ||
| export declare function requestOptions(options?: IRequestOptions): (pipeline: BaseRequest) => void; |
| import { PureModel, PureCollection, View } from '@datx/core'; | ||
| import { IHeaders } from './interfaces/IHeaders'; | ||
| import { IResponseInternal } from './interfaces/IResponseInternal'; | ||
| import { IResponseSnapshot } from './interfaces/IResponseSnapshot'; | ||
| import { IResponseObject } from './interfaces/IResponseObject'; | ||
| import { IResponseHeaders } from '@datx/utils'; | ||
| export declare class Response<T extends PureModel | Array<PureModel>> { | ||
| protected __data: any; | ||
| protected __internal: IResponseInternal; | ||
| /** | ||
| * Headers received from the API call | ||
| * | ||
| * @type {IResponseHeaders} | ||
| * @memberOf Response | ||
| */ | ||
| get headers(): IResponseHeaders | undefined; | ||
| /** | ||
| * Headers sent to the server | ||
| * | ||
| * @type {IHeaders} | ||
| * @memberOf Response | ||
| */ | ||
| get requestHeaders(): IHeaders | undefined; | ||
| /** | ||
| * Request error | ||
| * | ||
| * @type {(Array<JsonApi.IError>|Error)} | ||
| * @memberOf Response | ||
| */ | ||
| get error(): Array<string | object> | Error | undefined; | ||
| /** | ||
| * Received HTTP status | ||
| * | ||
| * @type {number} | ||
| * @memberOf Response | ||
| */ | ||
| get status(): number | undefined; | ||
| get views(): Array<View>; | ||
| /** | ||
| * Related Store | ||
| * | ||
| * @type {PureCollection} | ||
| * @memberOf Response | ||
| */ | ||
| readonly collection?: PureCollection; | ||
| /** | ||
| * Cache used for the link requests | ||
| * | ||
| * @protected | ||
| * @type {Record<string, Promise<Response>>} | ||
| * @memberOf Response | ||
| */ | ||
| protected readonly __cache: Record<string, () => Promise<Response<T>>>; | ||
| get isSuccess(): boolean; | ||
| get data(): T | null; | ||
| constructor(response: IResponseObject, collection?: PureCollection, overrideData?: T, views?: Array<View>); | ||
| private __updateInternal; | ||
| /** | ||
| * Replace the response record with a different record. Used to replace a record while keeping the same reference | ||
| * | ||
| * @param {PureModel} data New data | ||
| * @returns {Response} | ||
| * | ||
| * @memberOf Response | ||
| */ | ||
| replaceData(data: T): Response<T>; | ||
| clone(): Response<T>; | ||
| get snapshot(): IResponseSnapshot; | ||
| update(response: IResponseObject | Response<T>, views?: Array<View>): Response<T>; | ||
| } |
| import { PureCollection, PureModel, View } from '@datx/core'; | ||
| import { INetworkModel } from './interfaces/INetworkModel'; | ||
| import { INetworkView } from './interfaces/INetworkView'; | ||
| import { BaseRequest } from './BaseRequest'; | ||
| import { INetworkCollectionConstructor } from './interfaces/INetworkCollectionConstructor'; | ||
| interface INetwork<T> { | ||
| network?: BaseRequest; | ||
| new (): T; | ||
| } | ||
| export declare function withNetwork<T extends typeof PureModel>(Base: T): T & INetwork<INetworkModel>; | ||
| export declare function withNetwork<T extends typeof PureCollection>(Base: T): T & INetworkCollectionConstructor; | ||
| export declare function withNetwork<T extends typeof View>(Base: T): T & INetwork<INetworkView>; | ||
| export {}; |
-21
| MIT License | ||
| Copyright (c) 2021 Infinum | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
230120
163.08%0
-100%40
2.56%120
6.19%0
-100%515
-65.27%3
50%+ Added
+ Added
- Removed
- Removed
Updated
Updated