Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

datx-network

Package Overview
Dependencies
Maintainers
11
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

datx-network - npm Package Compare versions

Comparing version 2.0.0-beta.6 to 2.0.0-beta.7

dist/consts.d.ts

26

dist/BaseRequest.d.ts
import { PureModel } from 'datx';
import { IConfigType } from './interfaces/IConfigType';
import { IHeaders } from './interfaces/IHeaders';
import { IInterceptor } from './interfaces/IInterceptor';
import { IPipeOperator } from './interfaces/IPipeOperator';
import { Response } from './Response';
import { IResponseObject } from './interfaces/IResponseObject';
import { HttpMethod } from './enums/HttpMethod';
import { BodyType } from './enums/BodyType';
interface IHookOptions {
suspense?: boolean;
}
interface IRequestOptions {
method: HttpMethod;
url?: string;
params: Record<string, string>;
query: Record<string, string | Array<string> | object>;
headers: IHeaders;
body?: any;
bodyType: BodyType;
}
export declare class BaseRequest<TModel extends PureModel = PureModel, TParams extends object = {}> {
private _config;
private _options;
private _interceptors;
get config(): IConfigType;
get options(): IRequestOptions;
interceptors: Array<{
name: string;
fn: IInterceptor<TModel>;
}>;
constructor(baseUrl: string);
protected baseFetch(method: string, url: string, body?: string | FormData, requestHeaders?: IHeaders): Promise<IResponseObject>;
pipe<TNewModel extends PureModel = TModel, TNewParams extends object = TParams>(...operators: Array<IPipeOperator>): BaseRequest<TNewModel, TNewParams>;
private doRequest;
pipe<TNewModel extends PureModel | Array<PureModel> = TModel, TNewParams extends object = TParams>(...operators: Array<IPipeOperator | undefined>): BaseRequest<TNewModel, TNewParams>;
private processBody;

@@ -32,0 +18,0 @@ fetch(params?: TParams): Promise<Response<TModel>>;

import { PureModel } from 'datx';
export declare function decorateModel(BaseClass: typeof PureModel): typeof PureModel;
import { INetworkModelConstructor } from './interfaces/INetworkModelConstructor';
export declare function decorateModel(BaseClass: typeof PureModel): INetworkModelConstructor;
import { IConfigType } from './interfaces/IConfigType';
import { IHeaders } from './interfaces/IHeaders';
import { BaseRequest } from './BaseRequest';
import { PureModel } from 'datx';
import { IResponseObject } from './interfaces/IResponseObject';
/**
* Base implementation of the fetch function (can be overridden)
*
* @param {IConfigType} config The request config
* @param {string} method API call method
* @param {string} url API call URL
* @param {object} [body] API call body
* @param {IHeaders} [requestHeaders] Headers that will be sent
* @returns {Promise<IResponseObject>} Resolves with a raw response object
*/
export declare function baseFetch<TModel extends PureModel, TParams extends object>(requestObj: BaseRequest<TModel, TParams>, method: string, url: string, body?: string | FormData, requestHeaders?: IHeaders): Promise<IResponseObject>;
export declare function getDefaultConfig(): IConfigType;
import { ParamArrayType } from '../enums/ParamArrayType';
import { PureModel, IReferenceDefinition } from 'datx';
import { BaseRequest } from '../BaseRequest';
import { IRequestOptions } from '../interfaces/IRequestOptions';
export declare const isBrowser: boolean;

@@ -8,1 +10,2 @@ export declare function deepCopy<T extends object>(inObject: T): T;

export declare function getModelClassRefs(type: typeof PureModel | PureModel): Record<string, IReferenceDefinition>;
export declare function addOptionsToRequest<TModel, TParams extends object>(request: BaseRequest<TModel, TParams>, options?: IRequestOptions): BaseRequest<TModel, TParams>;

@@ -1,1 +0,1 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t,r=require("react"),n=require("mobx"),o=require("datx");(e=exports.CachingStrategy||(exports.CachingStrategy={}))[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",(t=exports.ParamArrayType||(exports.ParamArrayType={}))[t.MultipleParams=0]="MultipleParams",t[t.CommaSeparated=1]="CommaSeparated",t[t.ParamArray=2]="ParamArray";var i="undefined"!=typeof window;function a(e){var t,r;if("object"!=typeof e||null===e)return e;var n=Array.isArray(e)?[]:{};for(r in e)t=e[r],n[r]=a(t);return n}var s,c=/\{\s*([a-zA-Z0-9\-_]+)\s*\}/g;function u(e,t,r,n){return function(e,t){var r=e;if(t.length){var n="";-1===r.indexOf("?")?n="?":r.endsWith("&")||r.endsWith("?")||(n="&"),r+=n+t.join("&")}return r}(e,function e(t,r,n){void 0===n&&(n="");var o=[];return Object.keys(r).forEach((function(i){var a=""+n+(n?"["+i+"]":i);r[i]instanceof Array?t===exports.ParamArrayType.CommaSeparated?o.push({key:a,value:r[i].join(",")}):t===exports.ParamArrayType.MultipleParams?o.push.apply(o,r[i].map((function(e){return{key:a,value:e}}))):t===exports.ParamArrayType.ParamArray&&o.push.apply(o,r[i].map((function(e){return{key:a+"[]",value:e}}))):"object"==typeof r[i]?o.push.apply(o,e(t,r[i],a)):o.push({key:a,value:r[i]})})),o}(r,t).map((function(e){var t=e.key,r=e.value;return{key:t,value:n?encodeURIComponent(r):r}})).map((function(e){return e.key+"="+e.value})))}function p(e,t,r,n){var o,i=arguments.length,a=i<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,r,a):o(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a}function l(e){if(e instanceof Array)return e;var t=[];return e.forEach((function(e,r){t.push([r,e])})),t}function f(e,t,r){if(t&&e.data){var n=r||t.add(e.data);return new o.Bucket.ToOneOrMany(n,t,!0)}if(e.data&&e.data){if(e.data instanceof Array)throw new Error("A save/remove operation should not return an array of results");return{value:new o.PureModel(e.data)}}return new o.Bucket.ToOneOrMany(null,t,!0)}(s=exports.HttpMethod||(exports.HttpMethod={})).Get="GET",s.Post="POST",s.Put="PUT",s.Patch="Patch",s.Delete="Delete",s.Options="Options",s.Head="Head";var d,h=function(){function e(e,t,r,o,i){var a=this;this.__internal={response:{},views:[]},this.collection=t,n.runInAction((function(){if(a.__updateInternal(e,r,i),a.__data=f(e,t,o),a.views.forEach((function(e){a.__data.value&&e.add(a.__data.value)})),Object.freeze(a),a.error)throw a}))}return Object.defineProperty(e.prototype,"headers",{get:function(){return this.__internal.headers},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"requestHeaders",{get:function(){return this.__internal.requestHeaders},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"error",{get:function(){return this.__internal.error},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"status",{get:function(){return this.__internal.status},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"views",{get:function(){return this.__internal.views},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSuccess",{get:function(){return!this.error},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"data",{get:function(){return this.__data.value},enumerable:!1,configurable:!0}),e.prototype.__updateInternal=function(e,t,r){var n;t&&(this.__internal.options=t),this.__internal.response=e,this.__internal.headers=e.headers&&((n=e.headers)instanceof Array?new Headers(n):n),this.__internal.requestHeaders=e.requestHeaders,this.__internal.error=e.error,this.__internal.status=e.status,r&&(this.__internal.views=r),this.error||this.status||(this.__internal.error=new Error("Network not available"))},e.prototype.replaceData=function(t){var r=this.data;if(r===t)return this;var n=o.getModelId(r).toString(),i=o.getModelType(r),a=this.views.map((function(e){return e.list.indexOf(r)}));return this.collection&&(this.collection.removeOne(i,n),this.collection.add(t)),o.updateModel(t,o.modelToJSON(r)),o.updateModelId(t,n),this.views.forEach((function(e,r){-1!==a[r]&&(e.list[a[r]]=t)})),new e(this.__internal.response,this.collection,this.__internal.options,t)},e.prototype.clone=function(){return new e(this.__internal.response,this.collection,this.__internal.options,this.data||void 0)},Object.defineProperty(e.prototype,"snapshot",{get:function(){return{response:Object.assign({},this.__internal.response,{headers:this.__internal.response.headers&&l(this.__internal.response.headers),collection:void 0}),options:this.__internal.options}},enumerable:!1,configurable:!0}),e.prototype.update=function(e,t){this.__updateInternal(e,void 0,t);var r=f(e,this.collection);return this.__data.__readonlyValue=r.value,this},p([n.action],e.prototype,"replaceData",null),p([n.action],e.prototype,"update",null),e}(),y=[];function v(e,t,r,i,a){return void 0===i&&(i=!1),t(e).then((function(t){var n=Object.assign({},t,{collection:e.collection});return a?(a.update(n,e.views),a):new h(r.config.parse(n),e.collection,e.options,void 0,e.views)})).then((function(t){return i&&function(e,t){if(t&&t.isSuccess&&(t.data||null===t.data)){var r=(i=t.data||[],a=o.getModelType,n.isArrayLike(i)?i.map((function(e){return a(e)})):null===i?null:a(i));(y=y.filter((function(t){return t.url!==e}))).unshift({response:t.snapshot,collection:t.collection,time:Date.now(),types:[].concat(r),url:e})}var i,a}(e.url,t),t})).catch((function(t){var n=Object.assign({},t,{collection:e.collection});throw new h(r.config.parse(n),e.collection,e.options,void 0,e.views)}))}function g(e,t,r){var n,o;return new h({error:new Error(e),requestHeaders:null===(o=null===(n=t.options)||void 0===n?void 0:n.networkConfig)||void 0===o?void 0:o.headers},r,t.options)}!function(e){e[e.Raw=0]="Raw",e[e.Json=1]="Json",e[e.Multipart=2]="Multipart",e[e.Urlencoded=3]="Urlencoded"}(d||(d={}));var _=function(){function e(e){this._config={baseUrl:"/",cache:i?exports.CachingStrategy.CacheFirst:exports.CachingStrategy.NetworkOnly,maxCacheAge:1/0,defaultFetchOptions:{headers:{"content-type":"application/vnd.api+json"}},encodeQueryString:!0,fetchReference:i&&"fetch"in window&&"function"==typeof window.fetch&&window.fetch.bind(window)||void 0,paramArrayType:exports.ParamArrayType.ParamArray,serialize:function(e,t){return e},parse:function(e){return e}},this._options={method:exports.HttpMethod.Get,headers:{},query:{},params:{},bodyType:d.Json},this._interceptors=[],this._config.baseUrl=e}return Object.defineProperty(e.prototype,"config",{get:function(){return this._config},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),e.prototype.baseFetch=function(e,t,r,n){return function(e,t,r,n,o){var i;void 0===o&&(o={});var a,s=0,c=Promise.resolve(),u=t.toUpperCase(),p="GET"!==u&&"HEAD"!==u;return c.then((function(){var i=e.config.defaultFetchOptions.headers||{},a=Object.assign({},i,o),s=Object.assign({},e.config.defaultFetchOptions,{body:p&&n||void 0,headers:a,method:t});if(e.config.fetchReference)return e.config.fetchReference(r,s);throw new Error("Fetch reference needs to be defined before using the network")})).then((function(e){return s=e.status,a=e.headers,e.json()})).catch((function(e){if(204===s)return null;if(0===s)throw null;throw e})).then((function(t){if(i=t,s>=400)throw{message:"Invalid HTTP status: "+s,status:s};return{data:i,headers:a,requestHeaders:o,status:s,collection:e.config.collection}})).catch((function(t){throw{data:i,error:t,headers:a,requestHeaders:o,status:s,collection:e.config.collection}}))}(this,e,t,r,n)},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this.clone();return e.forEach((function(e){return e(r)})),r},e.prototype.doRequest=function(e){return this.baseFetch(e.method,e.url,e.data,this.options.headers).then((function(e){return{data:e.data,status:e.status,headers:e.headers,requestHeaders:e.requestHeaders,error:e.error,collection:e.collection}}),(function(e){return Promise.reject({data:e.data,status:e.status,headers:e.headers,requestHeaders:e.requestHeaders,error:e.error,collection:e.collection})}))},e.prototype.processBody=function(){if(this._options.body)return this._options.bodyType===d.Json?(this._options.headers["content-type"]="application/json","string"==typeof this._options.body?this._options.body:JSON.stringify(this._options.body)):this._options.bodyType===d.Urlencoded?(this._options.headers["content-type"]="application/x-www-form-urlencoded","string"==typeof this._options.body?this._options.body:u("",this._options.body,this._config.paramArrayType,this._config.encodeQueryString).slice(1)):this._options.bodyType===d.Multipart?(this._options.headers["content-type"]="multipart/form-data",this._options.body instanceof FormData?this._options.body:new FormData(this._options.body)):"string"==typeof this._options.body?this._options.body:JSON.stringify(this._options.body)},e.prototype.fetch=function(e){var t=this;if(!this.options.url)throw new Error("URL should be defined");var r=Object.assign({},this.options.params,e),n=u(function(e,t){for(var r=e,n=c.exec(r),o=0;n;){var i=t[n[1]];void 0===i&&(i=n[0],o=c.lastIndex),r=r.replace(n[0],i),c.lastIndex=o,n=c.exec(r)}return r}(this.options.url,r),this.options.query,this.config.paramArrayType,this.config.encodeQueryString);return this._interceptors.reverse().reduce((function(e,t){return function(r){return t(r,e)}}),(function(e){return(r=t._config.cache,n=t._config.maxCacheAge,o=t,function(e,t){var i,a,s,c,u,p=e.method===exports.HttpMethod.Get,l=(null===(a=null===(i=e.options)||void 0===i?void 0:i.cacheOptions)||void 0===a?void 0:a.skipCache)||!p?exports.CachingStrategy.NetworkOnly:(null===(c=null===(s=e.options)||void 0===s?void 0:s.cacheOptions)||void 0===c?void 0:c.cachingStrategy)||r;if(l===exports.CachingStrategy.NetworkOnly)return v(e,t,o);var f=function(e,t){var r=Date.now()-1e3*t,n=y.find((function(t){return t.url===e&&t.time>r}));if(n){var o=n.response;return{response:new h(o.response,n.collection,o.options),time:n.time,types:n.types,url:n.url}}}(e.url,n);if(l===exports.CachingStrategy.NetworkFirst)return v(e,t,o,!0).catch((function(e){if(f)return f.response;throw e}));if(l===exports.CachingStrategy.StaleWhileRevalidate){var d=v(e,t,o,!0);return f?(d.catch((function(){})),Promise.resolve(f.response)):d}if(l===exports.CachingStrategy.CacheOnly)return f?Promise.resolve(f.response):Promise.reject(g("No cache for this request",e,null==e?void 0:e.collection));if(l===exports.CachingStrategy.CacheFirst)return f?Promise.resolve(f.response):v(e,t,o,!0);if(l===exports.CachingStrategy.StaleAndUpdate){var _=null===(u=null==f?void 0:f.response)||void 0===u?void 0:u.clone();return d=v(e,t,o,!0,_),_?(d.catch((function(){})),Promise.resolve(_)):d}return Promise.reject(g("Invalid caching strategy",e,null==e?void 0:e.collection))})(e,t.doRequest.bind(t));var r,n,o}))({url:n,method:this._options.method,data:this.processBody()})},e.prototype.useHook=function(e,t){var n=this,o=r.useState(null),i=o[0],a=o[1],s=r.useState(null),c=s[0],u=s[1],p=r.useState(null),l=p[0],f=p[1],d=r.useCallback((function(){var t=n.fetch(e);return a(t),u(null),f(null),t.then((function(e){u(e),a(null)})).catch((function(e){f(e),a(null)}))}),[this.fetch,e]);if(r.useEffect((function(){d()}),[d]),(null==t?void 0:t.suspense)&&i)throw i;return[c,Boolean(i),l]},e.prototype.clone=function(e){void 0===e&&(e=this.constructor);var t=new e(this._config.baseUrl);return t._config=a(this._config),t._interceptors=this._interceptors.slice(),t._options=a(this._options),t.config.fetchReference=this.config.fetchReference,t},e}();exports.BaseRequest=_,exports.Response=h,exports.addInterceptor=function(e){return function(t){t._interceptors.push(e)}},exports.body=function(e,t){return function(r){t||0===t?r.options.bodyType=t:e instanceof FormData?r.options.bodyType=d.Multipart:r.options.bodyType="object"==typeof e?d.Json:d.Raw,r.options.body=r.config.serialize(e,r.options.bodyType)}},exports.cache=function(e,t){return void 0===t&&(t=1/0),function(r){r.config.cache=e,r.config.maxCacheAge=t}},exports.encodeQueryString=function(e){return function(t){t.config.encodeQueryString=e}},exports.fetchReference=function(e){return function(t){t.config.fetchReference=e}},exports.header=function(e,t){return function(r){r.options.headers[e]=t}},exports.method=function(e){return function(t){t.options.method=e}},exports.paramArrayType=function(e){return function(t){t.config.paramArrayType=e}},exports.params=function(e,t){return function(r){"string"==typeof e?r.options.params[e]=t:Object.assign(r.options.params,e)}},exports.parser=function(e){return function(t){t.config.parse=e}},exports.query=function(e,t){return function(r){r.options.query[e]=t}},exports.serializer=function(e){return function(t){t.config.serialize=e}},exports.setUrl=function(e){return function(t){t.options.url=e}};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("react"),n=require("mobx"),r=require("datx");(e=exports.ParamArrayType||(exports.ParamArrayType={}))[e.MultipleParams=0]="MultipleParams",e[e.CommaSeparated=1]="CommaSeparated",e[e.ParamArray=2]="ParamArray";var o,i=Symbol.for("datx administration");function a(e,t){return n.isArrayLike(e)?e.map((function(e){return t(e)})):null===e?null:t(e)}function s(e){return Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{configurable:!1,enumerable:!1,value:n.observable({},{},{deep:!1})}),e[i]}function c(e,t,r){var o=s(e);n.set(o,t,r)}function u(e,t,n,r,o){if(r)return function(e,t,n){for(var r=n,o=e;o;)r=t(r,o),o=Object.getPrototypeOf(o);return r}(e,(function(e,n){var r=u(n,t,o?{}:void 0);return o?Object.assign({},r,e):e||r}),o?{}:void 0)||n;var i=s(e);return void 0===i[t]?n:i[t]}!function(e){e[e.Raw=0]="Raw",e[e.Json=1]="Json",e[e.Multipart=2]="Multipart",e[e.Urlencoded=3]="Urlencoded"}(o||(o={}));var l=function(e,t){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function p(e,t){function n(){this.constructor=e}l(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var d=function(){return(d=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function f(e,t,n,r){var o,i=arguments.length,a=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function h(e){if(e instanceof Array)return e;var t=[];return e.forEach((function(e,n){t.push([n,e])})),t}function v(e,t,n){var o=null;if(t&&e.data)o=n||(e.type?t.add(e.data,e.type):t.add(e.data));else if(e.data){var i=e.type===r.PureModel||Object.isPrototypeOf.call(r.PureModel,e.type||{})?e.type:r.PureModel;return{value:o=n||a(e.data,(function(e){return new i(e)}))}}return new r.Bucket.ToOneOrMany(o,t,!0)}var y,g,w=function(){function e(e,t,r,o){var i=this;this.__internal={response:{},views:[]},this.collection=t,n.runInAction((function(){i.__updateInternal(e,o);try{i.__data=v(e,t,r)}catch(e){i.__internal.error=e}if(i.views.forEach((function(e){i.__data.value&&e.add(i.__data.value)})),Object.freeze(i),i.error)throw i}))}return Object.defineProperty(e.prototype,"headers",{get:function(){return this.__internal.headers},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"requestHeaders",{get:function(){return this.__internal.requestHeaders},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"error",{get:function(){return this.__internal.error},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"status",{get:function(){return this.__internal.status},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"views",{get:function(){return this.__internal.views},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSuccess",{get:function(){return!this.error},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"data",{get:function(){return this.__data.value},enumerable:!1,configurable:!0}),e.prototype.__updateInternal=function(e,t){var n;this.__internal.response=e,this.__internal.headers=e.headers&&((n=e.headers)instanceof Array?new Headers(n):n),this.__internal.requestHeaders=e.requestHeaders,this.__internal.error=e.error,this.__internal.status=e.status,t&&(this.__internal.views=t),this.error||this.status||(this.__internal.error=new Error("Network not available"))},e.prototype.replaceData=function(t){var n=this.data;if(n===t)return this;var o=r.getModelId(n).toString(),i=r.getModelType(n),a=this.views.map((function(e){return e.list.indexOf(n)}));return this.collection&&(this.collection.removeOne(i,o),this.collection.add(t)),r.updateModel(t,r.modelToJSON(n)),r.updateModelId(t,o),this.views.forEach((function(e,n){-1!==a[n]&&(e.list[a[n]]=t)})),new e(this.__internal.response,this.collection,t)},e.prototype.clone=function(){return new e(this.__internal.response,this.collection,this.data||void 0)},Object.defineProperty(e.prototype,"snapshot",{get:function(){return{response:Object.assign({},this.__internal.response,{headers:this.__internal.response.headers&&h(this.__internal.response.headers),collection:void 0})}},enumerable:!1,configurable:!0}),e.prototype.update=function(t,n){var r=t instanceof e?t.__internal.response:t;this.__updateInternal(r,n);var o=v(r,this.collection);return this.__data.__readonlyValue=o.value,this},f([n.action],e.prototype,"replaceData",null),f([n.action],e.prototype,"update",null),e}();(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",(g=exports.HttpMethod||(exports.HttpMethod={})).Get="GET",g.Post="POST",g.Put="PUT",g.Patch="Patch",g.Delete="Delete",g.Options="Options",g.Head="Head";var _=[];function m(e,t,n,o){return void 0===n&&(n=!1),t(e).then((function(t){var i=t;return o&&(i=o.update(t,e.views)),n&&function(e,t){if(t&&t.isSuccess&&(t.data||null===t.data)){var n=a(t.data||[],r.getModelType);(_=_.filter((function(t){return t.url!==e}))).unshift({response:t.snapshot,collection:t.collection,time:Date.now(),types:[].concat(n),url:e})}}(e.url,i),i}),(function(e){throw e}))}function b(e,t,n){var r,o;return new w({error:new Error(e),collection:n,requestHeaders:null===(o=null===(r=t.options)||void 0===r?void 0:r.networkConfig)||void 0===o?void 0:o.headers},n)}function O(e,t){return void 0===t&&(t=1/0),function(n,r){var o,i,a,s,c;if(!r)throw new Error("Cache interceptor can't be the last interceptor");var u=n.method.toUpperCase()===exports.HttpMethod.Get,l=(null===(i=null===(o=n.options)||void 0===o?void 0:o.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 m(n,r);var p=function(e,t){var n=Date.now()-1e3*t,r=_.find((function(t){return t.url===e&&t.time>n}));if(r){var o=r.response;return{response:new w(o.response,r.collection,o.options),time:r.time,types:r.types,url:r.url}}}(n.url,t);if(l===exports.CachingStrategy.NetworkFirst)return m(n,r,!0).catch((function(e){if(p)return p.response;throw e}));if(l===exports.CachingStrategy.StaleWhileRevalidate){var d=m(n,r,!0);return p?(d.catch((function(){})),Promise.resolve(p.response)):d}if(l===exports.CachingStrategy.CacheOnly)return p?Promise.resolve(p.response):Promise.reject(b("No cache for this request",n,null==n?void 0:n.collection));if(l===exports.CachingStrategy.CacheFirst)return p?Promise.resolve(p.response):m(n,r,!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=m(n,r,!0,f),f?(d.catch((function(){})),Promise.resolve(f)):d}return Promise.reject(b("Invalid caching strategy",n,null==n?void 0:n.collection))}}function k(e,t){return e.data?d(d({},e),{data:t(e.data,e)}):e}function P(e,t,n){return void 0===t&&(t=function(e){return e}),void 0===n&&(n=function(e){return e}),function(r,o){var i,a;if(!e)throw new Error("The fetch reference must be defined");var s,c,u=t?t(r):r,l=0,p=u.method.toUpperCase(),d="GET"!==p&&"HEAD"!==p,f="object"!=typeof u.data||u.data instanceof FormData?u.data:JSON.stringify(u.data),h=d?f:void 0,v=Object.assign({},null===(a=null===(i=u.options)||void 0===i?void 0:i.networkConfig)||void 0===a?void 0:a.headers),y=Object.assign({body:h,headers:v,method:u.method});return e(u.url,y).then((function(e){return l=e.status,c=e.headers,e.json()})).catch((function(e){if(204===l)return null;if(0===l)throw new Error("Network not available");throw e})).then((function(e){if(s=e,l>=400)throw{message:"Invalid HTTP status: "+l,status:l};var t=k({data:s,headers:c,requestHeaders:v,status:l,collection:r.collection,type:r.type},n);return new w(t,r.collection,void 0,r.views)})).catch((function(e){var t=k({data:s,error:e,headers:c,requestHeaders:v,status:l,collection:r.collection,type:r.type},n);throw new w(t,r.collection,void 0,r.views)}))}}function x(e,t){return void 0===t&&(t=r.PureModel),function(n){n._options.url=e,n._config.type=t}}function S(e,t){return void 0===t&&(t=e.name),function(n){var r=n.interceptors.find((function(e){return e.name===t}));r?r.fn=e:n.interceptors.push({name:t,fn:e})}}function T(e,t){return void 0===t&&(t=1/0),S(O(e,t),"cache")}function j(e){return function(t){t._options.method=e}}function C(e,t){return function(n){t||0===t?n._options.bodyType=t:e instanceof FormData?n._options.bodyType=o.Multipart:n._options.bodyType="object"==typeof e?o.Json:o.Raw,n._options.body=e}}function M(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)}}var E="undefined"!=typeof window;function q(e){var t,n;if("object"!=typeof e||null===e)return e;var r=Array.isArray(e)?[]:{};for(n in e)t=e[n],r[n]=q(t);return r}var H=/\{\s*([a-zA-Z0-9\-_]+)\s*\}/g;function R(e,t,n,r){return function(e,t){var n=e;if(t.length){var r="";-1===n.indexOf("?")?r="?":n.endsWith("&")||n.endsWith("?")||(r="&"),n+=r+t.join("&")}return n}(e,function e(t,n,r){void 0===r&&(r="");var o=[];return Object.keys(n).forEach((function(i){var a=""+r+(r?"["+i+"]":i);n[i]instanceof Array?t===exports.ParamArrayType.CommaSeparated?o.push({key:a,value:n[i].join(",")}):t===exports.ParamArrayType.MultipleParams?o.push.apply(o,n[i].map((function(e){return{key:a,value:e}}))):t===exports.ParamArrayType.ParamArray&&o.push.apply(o,n[i].map((function(e){return{key:a+"[]",value:e}}))):"object"==typeof n[i]?o.push.apply(o,e(t,n[i],a)):o.push({key:a,value:n[i]})})),o}(n,t).map((function(e){var t=e.key,n=e.value;return{key:t,value:r?encodeURIComponent(n):n}})).map((function(e){return e.key+"="+e.value})))}function U(e,t){var n,r,o,i,a;return e.pipe((null==t?void 0:t.query)&&M(null==t?void 0:t.query),(null===(n=null==t?void 0:t.networkConfig)||void 0===n?void 0:n.headers)&&A(null===(r=null==t?void 0:t.networkConfig)||void 0===r?void 0:r.headers),(null===(o=null==t?void 0:t.cacheOptions)||void 0===o?void 0:o.cachingStrategy)&&T(null===(i=null==t?void 0:t.cacheOptions)||void 0===i?void 0:i.cachingStrategy,null===(a=null==t?void 0:t.cacheOptions)||void 0===a?void 0:a.maxAge))}var N=function(){function e(e){var t,n;this._config={baseUrl:"/",encodeQueryString:!0,paramArrayType:exports.ParamArrayType.ParamArray,fetchReference:E?null===(n=null===(t=window.fetch)||void 0===t?void 0:t.bind)||void 0===n?void 0:n.call(t,window):void 0},this._options={method:exports.HttpMethod.Get,headers:{},query:{},params:{},bodyType:o.Json},this.interceptors=[{fn:P(this._config.fetchReference,this._config.serialize,this._config.parse),name:"fetch"},{fn:O(E?exports.CachingStrategy.CacheFirst:exports.CachingStrategy.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===o.Json?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/json",this._options.body):this._options.bodyType===o.Urlencoded?(this._options.headers["content-type"]=this._options.headers["content-type"]||"application/x-www-form-urlencoded","string"==typeof this._options.body?this._options.body:R("",this._options.body,this._config.paramArrayType,this._config.encodeQueryString).slice(1)):this._options.bodyType===o.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){if(!this._options.url)throw new Error("URL should be defined");var t=Object.assign({},this._options.params,e),n={url:R(function(e,t){for(var n=e,r=H.exec(n),o=0;r;){var i=t[r[1]];void 0===i&&(i=r[0],o=H.lastIndex),n=n.replace(r[0],i),H.lastIndex=o,r=H.exec(n)}return n}(""+this._config.baseUrl+this._options.url,t),this._options.query,this._config.paramArrayType,this._config.encodeQueryString),method:this._options.method,data:this.processBody(),collection:this._config.collection,options:{networkConfig:{headers:this._options.headers}},views:this._config.views,type:this._config.type},r=this.interceptors.reduce((function(e,t){return function(n){return t.fn(n,e)}}),void 0);if(!r)throw new Error("Something went wrong");return r(n)},e.prototype.useHook=function(e,n){var r=this,o=t.useState(null),i=o[0],a=o[1],s=t.useState(null),c=s[0],u=s[1],l=t.useState(null),p=l[0],d=l[1],f=t.useCallback((function(){var t=r.fetch(e);return a(t),u(null),d(null),t.then((function(e){u(e),a(null)})).catch((function(e){d(e),a(null)}))}),[this.fetch,e]);if(t.useEffect((function(){f()}),[f]),(null==n?void 0:n.suspense)&&i)throw i;return[c,Boolean(i),p]},e.prototype.clone=function(e){void 0===e&&(e=this.constructor);var t=new e(this._config.baseUrl);return t.interceptors=q(this.interceptors),t._config=q(this._config),t._options=q(this._options),t._config.collection=this._config.collection,t._config.type=this._config.type,t},e}(),D=["networkPersisted"];exports.BaseRequest=N,exports.Response=w,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=C,exports.cache=T,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,S(P(n.fetchReference,n.serialize,n.parse),"fetch")(t)}},exports.header=A,exports.method=j,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,S(P(n.fetchReference,n.serialize,n.parse),"fetch")(t)}},exports.query=M,exports.serializer=function(e){return function(t){var n=t._config;n.serialize=e,S(P(n.fetchReference,n.serialize,n.parse),"fetch")(t)}},exports.setUrl=x,exports.withNetwork=function(e){if(r.isModel(e))return function(e){function t(t,n){void 0===t&&(t={});var r=e.call(this,t,n)||this,o=(null==t?void 0:t.__META__)||{};return D.forEach((function(e){e in o&&c(r,e,o[e])})),r}return p(t,e),t.prototype.save=function(e){return function(e,t){var o,i,a,s,l,p=e.constructor;if(!p.network)throw new Error("The network property needs to be defined on the model");var d,f,h=u(e,"networkPersisted",!1);if(!(d=p.network instanceof N?h?p.network.pipe(j(exports.HttpMethod.Put),x(p.network._options.url+"/{id}",p)):p.network.pipe(j(exports.HttpMethod.Post)):h?p.network.update:p.network.create))throw new Error("The base request has not been defined");return d.pipe((null==t?void 0:t.query)&&M(null==t?void 0:t.query),(null===(o=null==t?void 0:t.networkConfig)||void 0===o?void 0:o.headers)&&A(null===(i=null==t?void 0:t.networkConfig)||void 0===i?void 0:i.headers),(null===(a=null==t?void 0:t.cacheOptions)||void 0===a?void 0:a.cachingStrategy)&&T(null===(s=null==t?void 0:t.cacheOptions)||void 0===s?void 0:s.cachingStrategy,null===(l=null==t?void 0:t.cacheOptions)||void 0===l?void 0:l.maxAge),C(r.modelToJSON(e))).fetch().then((f=e,n.action((function(e){if(e.error)throw e.error;if(204===e.status)return c(f,"networkPersisted",!0),f;c(f,"networkPersisted",!0);var t=e.replaceData(f).data||f;return r.commitModel(t),t}))))}(this,e)},t.prototype.destroy=function(e){return function(e,t){var n,o,i,a,s,c=e.constructor;if(!c.network)throw new Error("The network property needs to be defined on the model");var l,p=u(e,"networkPersisted",!1);if(!(l=c.network instanceof N?!!p&&c.network.pipe(j(exports.HttpMethod.Delete),x(c.network._options.url+"/{id}",c)):!!p&&c.network.destroy)&&!1!==l)throw new Error("The base request has not been defined");return l&&l.pipe((null==t?void 0:t.query)&&M(null==t?void 0:t.query),(null===(n=null==t?void 0:t.networkConfig)||void 0===n?void 0:n.headers)&&A(null===(o=null==t?void 0:t.networkConfig)||void 0===o?void 0:o.headers),(null===(i=null==t?void 0:t.cacheOptions)||void 0===i?void 0:i.cachingStrategy)&&T(null===(a=null==t?void 0:t.cacheOptions)||void 0===a?void 0:a.cachingStrategy,null===(s=null==t?void 0:t.cacheOptions)||void 0===s?void 0:s.maxAge)).fetch().then((function(){var t=r.getModelCollection(e);t&&t.removeOne(e)})),Promise.resolve()}(this,e)},t}(e);if(r.isCollection(e))return function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return p(t,e),t.prototype.getConstructor=function(e){return r.getModelType(e)},t.prototype.getOne=function(e,t,n){var r=this.getConstructor(e);if(!r||!r.network)throw new Error("The network configuration is wrong for the given model");if(r.network instanceof N)return U(r.network.pipe(x(r.network._options.url+"/{id}",r)),n).fetch({id:t});if(!r.network.getOne)throw new Error("The getOne network request was not defined on the given model");return U(r.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 N)return U(n.network,t).fetch();if(!n.network.getMany)throw new Error("The getMany network request was not defined on the given model");return U(n.network.getMany,t).fetch()},t.prototype.removeOne=function(t,n,o){var i=this,a=r.getModelType(t),s="object"!=typeof n&&void 0!==n&&"boolean"!=typeof n?n:null,c=null!==s?o:n,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)):u.destroy("object"==typeof c?c:{}).then((function(){e.prototype.removeOne.call(i,u)}))},t}(e);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, } from './operators';
export { addInterceptor, cache, method, setUrl, body, query, header, params, fetchReference, encodeQueryString, paramArrayType, serializer, parser, collection, } from './operators';
export { CachingStrategy } from './enums/CachingStrategy';

@@ -13,1 +13,6 @@ export { HttpMethod } from './enums/HttpMethod';

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 { useState, useCallback, useEffect } from 'react';
import { isArrayLike, action, runInAction } from 'mobx';
import { getModelId, getModelType, updateModel, modelToJSON, updateModelId, Bucket, PureModel } from 'datx';
import { isArrayLike, set, observable, action, runInAction } from 'mobx';
import { getModelId, getModelType, updateModel, modelToJSON, updateModelId, PureModel, Bucket, commitModel, getModelCollection, isModel, isCollection } from 'datx';
// 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 ParamArrayType;

@@ -23,2 +12,14 @@ (function (ParamArrayType) {

var META_FIELD = '__META__'; // Note: Hardcoded in interfaces/IRawModel
var DATX_META = Symbol.for('datx administration');
function reducePrototypeChain(obj, reduceFn, initialValue) {
var value = initialValue;
var model = obj;
while (model) {
value = reduceFn(value, model);
model = Object.getPrototypeOf(model);
}
return value;
}
function mapItems(data, fn) {

@@ -30,203 +31,36 @@ if (isArrayLike(data)) {

}
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
function getMetaObj(obj) {
if (!Object.prototype.hasOwnProperty.call(obj, DATX_META)) {
Object.defineProperty(obj, DATX_META, {
configurable: false,
enumerable: false,
value: observable({}, {}, { deep: false }),
});
}
// 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;
// @ts-ignore https://github.com/microsoft/TypeScript/issues/1863
return obj[DATX_META];
}
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 setMeta(obj, key, value) {
var meta = getMetaObj(obj);
set(meta, key, value);
}
function parametrize(paramArrayType, params, scope) {
if (scope === void 0) { scope = ''; }
var list = [];
Object.keys(params).forEach(function (key) {
var scoped = "" + scope + (scope ? "[" + 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: scoped + "[]",
value: param,
}); }));
}
}
else if (typeof params[key] === 'object') {
list.push.apply(list, parametrize(paramArrayType, params[key], scoped));
}
else {
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('&');
function getMeta(obj, key, defaultValue, includeChain, mergeChain) {
if (includeChain) {
return (reducePrototypeChain(obj, function (value, model) {
var meta = getMeta(model, key, mergeChain ? {} : undefined);
return mergeChain ? Object.assign({}, meta, value) : (value || meta);
}, (mergeChain ? {} : undefined)) || defaultValue);
}
return newUrl;
var meta = getMetaObj(obj);
return meta[key] === undefined ? defaultValue : meta[key];
}
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 key + "=" + value;
});
return appendParams(url, processedParams);
}
/**
* Base implementation of the fetch function (can be overridden)
*
* @param {IConfigType} config The request config
* @param {string} method API call method
* @param {string} url API call URL
* @param {object} [body] API call body
* @param {IHeaders} [requestHeaders] Headers that will be sent
* @returns {Promise<IResponseObject>} Resolves with a raw response object
*/
function baseFetch(requestObj, method, url, body, requestHeaders) {
if (requestHeaders === void 0) { requestHeaders = {}; }
var data;
var status = 0;
var headers;
var request = Promise.resolve();
var uppercaseMethod = method.toUpperCase();
var isBodySupported = uppercaseMethod !== 'GET' && uppercaseMethod !== 'HEAD';
return request
.then(function () {
var defaultHeaders = requestObj.config.defaultFetchOptions.headers || {};
var reqHeaders = Object.assign({}, defaultHeaders, requestHeaders);
var options = Object.assign({}, requestObj.config.defaultFetchOptions, {
body: (isBodySupported && body) || undefined,
headers: reqHeaders,
method: method,
});
if (requestObj.config.fetchReference) {
return requestObj.config.fetchReference(url, options);
}
throw new Error('Fetch reference needs to be defined before using the network');
})
.then(function (response) {
status = response.status;
headers = response.headers;
return response.json();
})
.catch(function (error) {
if (status === 204) {
return null;
}
if (status === 0) {
throw null;
}
throw error;
})
.then(function (responseData) {
data = responseData;
if (status >= 400) {
throw {
message: "Invalid HTTP status: " + status,
status: status,
};
}
return { data: data, headers: headers, requestHeaders: requestHeaders, status: status, collection: requestObj.config.collection };
})
.catch(function (error) {
throw {
data: data,
error: error,
headers: headers,
requestHeaders: requestHeaders,
status: status,
collection: requestObj.config.collection,
};
});
}
function getDefaultConfig() {
return {
// Base URL for all API calls
baseUrl: '/',
// Enable caching by default in the browser
cache: isBrowser ? CachingStrategy.CacheFirst : CachingStrategy.NetworkOnly,
maxCacheAge: Infinity,
// Default options that will be passed to the fetch function
defaultFetchOptions: {
headers: {
'content-type': 'application/vnd.api+json',
},
},
encodeQueryString: true,
// Reference of the fetch method that should be used
fetchReference: (isBrowser &&
'fetch' in window &&
typeof window.fetch === 'function' &&
window.fetch.bind(window)) ||
undefined,
// Determines how will the request param arrays be stringified
paramArrayType: ParamArrayType.ParamArray,
serialize: function (data, _type) {
return data;
},
parse: function (data) {
return data;
},
};
}
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 = {}));
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 = {}));
/*! *****************************************************************************

@@ -246,3 +80,28 @@ Copyright (c) Microsoft Corporation. All rights reserved.

***************************************************************************** */
/* 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 (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
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 __decorate(decorators, target, key, desc) {

@@ -272,21 +131,21 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

function initData(response, collection, overrideData) {
var data = null;
if (collection && response.data) {
var data = overrideData || collection.add(response.data);
return new Bucket.ToOneOrMany(data, collection, true);
data =
overrideData ||
(response.type
? collection.add(response.data, response.type)
: collection.add(response.data));
}
if (response.data) {
// The case when a record is not in a store and save/remove are used
if (response.data) {
if (response.data instanceof Array) {
throw new Error('A save/remove operation should not return an array of results');
}
return {
value: new PureModel(response.data),
};
}
else if (response.data) {
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(null, collection, true);
return new Bucket.ToOneOrMany(data, collection, true);
}
var Response = /** @class */ (function () {
function Response(response, collection, options, overrideData, views) {
function Response(response, collection, overrideData, views) {
var _this = this;

@@ -299,4 +158,9 @@ this.__internal = {

runInAction(function () {
_this.__updateInternal(response, options, views);
_this.__data = initData(response, collection, overrideData);
_this.__updateInternal(response, views);
try {
_this.__data = initData(response, collection, overrideData);
}
catch (e) {
_this.__internal.error = e;
}
_this.views.forEach(function (view) {

@@ -386,6 +250,3 @@ if (_this.__data.value) {

});
Response.prototype.__updateInternal = function (response, options, views) {
if (options) {
this.__internal.options = options;
}
Response.prototype.__updateInternal = function (response, views) {
this.__internal.response = response;

@@ -430,6 +291,6 @@ this.__internal.headers = response.headers && initHeaders(response.headers);

});
return new Response(this.__internal.response, this.collection, this.__internal.options, data);
return new Response(this.__internal.response, this.collection, data);
};
Response.prototype.clone = function () {
return new Response(this.__internal.response, this.collection, this.__internal.options, this.data || undefined);
return new Response(this.__internal.response, this.collection, this.data || undefined);
};

@@ -443,3 +304,2 @@ Object.defineProperty(Response.prototype, "snapshot", {

}),
options: this.__internal.options,
};

@@ -451,4 +311,5 @@ },

Response.prototype.update = function (response, views) {
this.__updateInternal(response, undefined, views);
var newData = initData(response, this.collection);
var responseData = response instanceof Response ? response.__internal.response : response;
this.__updateInternal(responseData, views);
var newData = initData(responseData, this.collection);
this.__data.__readonlyValue = newData.value;

@@ -466,2 +327,24 @@ return this;

// 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 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 = {}));
var cacheStorage = [];

@@ -496,22 +379,15 @@ function saveCache(url, response) {

}
function makeNetworkCall(params, next, networkPipeline, doCacheResponse, existingResponse) {
function makeNetworkCall(params, next, doCacheResponse, existingResponse) {
if (doCacheResponse === void 0) { doCacheResponse = false; }
return next(params)
.then(function (response) {
var collectionResponse = Object.assign({}, response, { collection: params.collection });
return next(params).then(function (response) {
var finalResponse = response;
if (existingResponse) {
existingResponse.update(collectionResponse, params.views);
return existingResponse;
finalResponse = existingResponse.update(response, params.views);
}
return new Response(networkPipeline.config.parse(collectionResponse), params.collection, params.options, undefined, params.views);
})
.then(function (response) {
if (doCacheResponse) {
saveCache(params.url, response);
saveCache(params.url, finalResponse);
}
return response;
})
.catch(function (response) {
var collectionResponse = Object.assign({}, response, { collection: params.collection });
throw new Response(networkPipeline.config.parse(collectionResponse), params.collection, params.options, undefined, params.views);
return finalResponse;
}, function (response) {
throw response;
});

@@ -523,10 +399,14 @@ }

error: new Error(message),
// collection,
collection: collection,
requestHeaders: (_b = (_a = reqOptions.options) === null || _a === void 0 ? void 0 : _a.networkConfig) === null || _b === void 0 ? void 0 : _b.headers,
}, collection, reqOptions.options);
}, collection);
}
function cacheInterceptor(cache, maxCacheAge, networkPipeline) {
function cacheInterceptor(cache, maxCacheAge) {
if (maxCacheAge === void 0) { maxCacheAge = Infinity; }
return function (request, next) {
var _a, _b, _c, _d, _e;
var isCacheSupported = request.method === HttpMethod.Get;
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

@@ -537,3 +417,3 @@ ? CachingStrategy.NetworkOnly

if (cacheStrategy === CachingStrategy.NetworkOnly) {
return makeNetworkCall(request, next, networkPipeline);
return makeNetworkCall(request, next);
}

@@ -543,3 +423,3 @@ var cacheContent = getCache(request.url, maxCacheAge);

if (cacheStrategy === CachingStrategy.NetworkFirst) {
return makeNetworkCall(request, next, networkPipeline, true).catch(function (errorResponse) {
return makeNetworkCall(request, next, true).catch(function (errorResponse) {
if (cacheContent) {

@@ -553,3 +433,3 @@ return cacheContent.response;

if (cacheStrategy === CachingStrategy.StaleWhileRevalidate) {
var network = makeNetworkCall(request, next, networkPipeline, true);
var network = makeNetworkCall(request, next, true);
if (cacheContent) {

@@ -574,3 +454,3 @@ network.catch(function () {

? Promise.resolve(cacheContent.response)
: makeNetworkCall(request, next, networkPipeline, true);
: makeNetworkCall(request, next, true);
}

@@ -580,3 +460,3 @@ // StaleAndUpdate - Use cache and update response once network is complete

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, networkPipeline, true, existingResponse);
var network = makeNetworkCall(request, next, true, existingResponse);
if (existingResponse) {

@@ -594,10 +474,307 @@ network.catch(function () {

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 parseResponse(response, parse) {
if (response.data) {
return __assign(__assign({}, response), { data: parse(response.data, response) });
}
return response;
}
function fetchInterceptor(fetchReference, serialize, parse) {
if (serialize === void 0) { serialize = function (options) { return options; }; }
if (parse === void 0) { parse = function (data) { return data; }; }
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: " + status,
status: status,
};
}
var response = parseResponse({
data: data,
headers: headers,
requestHeaders: requestHeaders,
status: status,
collection: request.collection,
type: request.type,
}, parse);
return new Response(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(response, request.collection, undefined, request.views);
});
};
}
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(fetchInterceptor(config.fetchReference, config.serialize, config.parse), 'fetch')(pipeline);
};
}
function serializer(serialize) {
return function (pipeline) {
var config = pipeline['_config'];
config.serialize = serialize;
upsertInterceptor(fetchInterceptor(config.fetchReference, config.serialize, config.parse), 'fetch')(pipeline);
};
}
function parser(parse) {
return function (pipeline) {
var config = pipeline['_config'];
config.parse = parse;
upsertInterceptor(fetchInterceptor(config.fetchReference, config.serialize, config.parse), 'fetch')(pipeline);
};
}
function collection(collection) {
return function (pipeline) {
pipeline['_config'].collection = collection;
};
}
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 = "" + scope + (scope ? "[" + 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: scoped + "[]",
value: param,
}); }));
}
}
else if (typeof params[key] === 'object') {
list.push.apply(list, parametrize(paramArrayType, params[key], scoped));
}
else {
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 key + "=" + value;
});
return appendParams(url, processedParams);
}
function addOptionsToRequest(request, options) {
var _a, _b, _c, _d, _e;
return request.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));
}
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,
};
}
var BaseRequest = /** @class */ (function () {

@@ -613,22 +790,14 @@ function BaseRequest(baseUrl) {

};
this._interceptors = [];
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;
}
Object.defineProperty(BaseRequest.prototype, "config", {
get: function () {
return this._config;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BaseRequest.prototype, "options", {
get: function () {
return this._options;
},
enumerable: false,
configurable: true
});
BaseRequest.prototype.baseFetch = function (method, url, body, requestHeaders) {
return baseFetch(this, method, url, body, requestHeaders);
};
BaseRequest.prototype.pipe = function () {

@@ -640,26 +809,7 @@ var operators = [];

var destinationPipeline = this.clone();
operators.forEach(function (operator) { return operator(destinationPipeline); });
operators
.filter(Boolean)
.forEach(function (operator) { return operator(destinationPipeline); });
return destinationPipeline;
};
BaseRequest.prototype.doRequest = function (options) {
return this.baseFetch(options.method, options.url, options.data, this.options.headers).then(function (resp) {
return {
data: resp.data,
status: resp.status,
headers: resp.headers,
requestHeaders: resp.requestHeaders,
error: resp.error,
collection: resp.collection,
};
}, function (resp) {
return Promise.reject({
data: resp.data,
status: resp.status,
headers: resp.headers,
requestHeaders: resp.requestHeaders,
error: resp.error,
collection: resp.collection,
});
});
};
BaseRequest.prototype.processBody = function () {

@@ -670,9 +820,9 @@ if (!this._options.body) {

if (this._options.bodyType === BodyType.Json) {
this._options.headers['content-type'] = 'application/json';
return typeof this._options.body === 'string'
? this._options.body
: JSON.stringify(this._options.body);
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'] = 'application/x-www-form-urlencoded';
this._options.headers['content-type'] =
this._options.headers['content-type'] || 'application/x-www-form-urlencoded';
return typeof this._options.body === 'string'

@@ -683,3 +833,4 @@ ? this._options.body

else if (this._options.bodyType === BodyType.Multipart) {
this._options.headers['content-type'] = 'multipart/form-data';
this._options.headers['content-type'] =
this._options.headers['content-type'] || 'multipart/form-data';
return this._options.body instanceof FormData

@@ -690,28 +841,32 @@ ? this._options.body

else {
return typeof this._options.body === 'string'
? this._options.body
: JSON.stringify(this._options.body);
return this._options.body;
}
};
BaseRequest.prototype.fetch = function (params) {
var _this = this;
if (!this.options.url) {
if (!this._options.url) {
throw new Error('URL should be defined');
}
var urlParams = Object.assign({}, this.options.params, params);
var url = interpolateParams(this.options.url, urlParams);
var processedUrl = appendQueryParams(url, this.options.query, this.config.paramArrayType, this.config.encodeQueryString);
var initialCallback = this._interceptors.reverse().reduce(function (callback, interceptor) {
return function (options) {
return interceptor(options, callback);
};
}, function (options) {
return cacheInterceptor(_this._config.cache, _this._config.maxCacheAge, _this)(options, _this.doRequest.bind(_this));
});
// The error is not handled on purpose so UnhandledPromiseRejectionWarning is triggered if the client doesn't handle the error
return initialCallback({
var urlParams = Object.assign({}, this._options.params, params);
var url = interpolateParams("" + this._config.baseUrl + this._options.url, urlParams);
var processedUrl = appendQueryParams(url, this._options.query, this._config.paramArrayType, this._config.encodeQueryString);
var request = {
url: processedUrl,
method: this._options.method,
data: this.processBody(),
});
collection: this._config.collection,
options: {
networkConfig: {
headers: this._options.headers,
},
},
views: this._config.views,
type: this._config.type,
};
var interceptorChain = this.interceptors.reduce(function (next, interceptor) {
return function (options) { return interceptor.fn(options, next); };
}, undefined);
if (!interceptorChain) {
throw new Error('Something went wrong');
}
return interceptorChain(request);
};

@@ -750,6 +905,9 @@ BaseRequest.prototype.useHook = function (params, options) {

var clone = new BaseRequestConstructor(this._config.baseUrl);
// @ts-ignore
clone.interceptors = deepCopy(this.interceptors);
clone._config = deepCopy(this._config);
clone._interceptors = this._interceptors.slice();
clone._options = deepCopy(this._options);
clone.config.fetchReference = this.config.fetchReference;
// Manually copy complex objects
clone._config.collection = this._config.collection;
clone._config.type = this._config.type;
return clone;

@@ -760,87 +918,182 @@ };

function setUrl(url) {
return function (pipeline) {
pipeline.options.url = url;
};
function decorateCollection(BaseClass) {
var NetworkCollection = /** @class */ (function (_super) {
__extends(NetworkCollection, _super);
function NetworkCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
NetworkCollection.prototype.getConstructor = function (type) {
return getModelType(type);
};
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 addOptionsToRequest(root.network.pipe(setUrl(root.network['_options'].url + "/{id}", root)), options).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));
}
return model
.destroy(typeof realOptions === 'object' ? realOptions : {})
.then(function () {
_super.prototype.removeOne.call(_this, model);
});
};
return NetworkCollection;
}(BaseClass));
return NetworkCollection;
}
function addInterceptor(interceptor) {
return function (pipeline) {
pipeline['_interceptors'].push(interceptor);
};
}
function cache(strategy, maxAge) {
if (maxAge === void 0) { maxAge = Infinity; }
return function (pipeline) {
pipeline.config.cache = strategy;
pipeline.config.maxCacheAge = maxAge;
};
}
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;
var NETWORK_PERSISTED = 'networkPersisted';
function handleResponse(record) {
return action(function (response) {
if (response.error) {
throw response.error;
}
else if (body instanceof FormData) {
pipeline.options.bodyType = BodyType.Multipart;
if (response.status === 204) {
setMeta(record, NETWORK_PERSISTED, true);
return record;
}
else if (typeof body === 'object') {
pipeline.options.bodyType = BodyType.Json;
}
else {
pipeline.options.bodyType = BodyType.Raw;
}
pipeline.options.body = pipeline.config.serialize(body, pipeline.options.bodyType);
};
setMeta(record, NETWORK_PERSISTED, true);
var data = response.replaceData(record).data || record;
commitModel(data);
return data;
});
}
function query(name, value) {
return function (pipeline) {
pipeline.options.query[name] = value;
};
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(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(modelToJSON(model)));
return request.fetch().then(handleResponse(model));
}
function header(name, value) {
return function (pipeline) {
pipeline.options.headers[name] = value;
};
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(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()
.then(function () {
var collection = getModelCollection(model);
if (collection) {
collection.removeOne(model);
}
});
}
return Promise.resolve();
}
function params(name, value) {
return function (pipeline) {
if (typeof name === 'string') {
pipeline.options.params[name] = value;
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;
}
else {
Object.assign(pipeline.options.params, name);
}
};
NetworkModel.prototype.save = function (options) {
return saveModel(this, options);
};
NetworkModel.prototype.destroy = function (options) {
return removeModel(this, options);
};
return NetworkModel;
}(BaseClass));
return NetworkModel;
}
function fetchReference(fetchReference) {
return function (pipeline) {
pipeline.config.fetchReference = fetchReference;
};
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');
}
function encodeQueryString(encodeQueryString) {
return function (pipeline) {
pipeline.config.encodeQueryString = encodeQueryString;
};
}
function paramArrayType(paramArrayType) {
return function (pipeline) {
pipeline.config.paramArrayType = paramArrayType;
};
}
function serializer(serialize) {
return function (pipeline) {
pipeline.config.serialize = serialize;
};
}
function parser(parse) {
return function (pipeline) {
pipeline.config.parse = parse;
};
}
export { BaseRequest, CachingStrategy, HttpMethod, ParamArrayType, Response, addInterceptor, body, cache, encodeQueryString, fetchReference, header, method, paramArrayType, params, parser, query, serializer, setUrl };
export { BaseRequest, CachingStrategy, HttpMethod, ParamArrayType, Response, addInterceptor, body, cache, collection, encodeQueryString, fetchReference, header, method, paramArrayType, params, parser, query, serializer, setUrl, withNetwork };

@@ -1,17 +0,15 @@

import { CachingStrategy } from '../enums/CachingStrategy';
import { PureCollection, IType, PureModel, View } from 'datx';
import { ParamArrayType } from '../enums/ParamArrayType';
import { IFetchOptions } from './IFetchOptions';
import { IResponseObject } from './IResponseObject';
import { BodyType } from '../enums/BodyType';
import { PureCollection } from 'datx';
export interface IConfigType {
baseUrl: string;
cache: CachingStrategy;
maxCacheAge: number;
defaultFetchOptions: Record<string, any>;
fetchReference?: typeof fetch;
paramArrayType: ParamArrayType;
encodeQueryString: boolean;
serialize(data: IResponseObject, type: BodyType): IResponseObject;
parse(data: IResponseObject): IResponseObject;
collection?: PureCollection;
type?: IType | typeof PureModel;
views?: Array<View>;
fetchReference?: typeof fetch;
serialize?: (options: IFetchOptions) => IFetchOptions;
parse?: (data: object, options: IResponseObject) => object;
}

@@ -1,2 +0,2 @@

import { View, PureCollection } from 'datx';
import { View, PureCollection, IType, PureModel } from 'datx';
import { IRequestOptions } from './IRequestOptions';

@@ -7,3 +7,3 @@ import { HttpMethod } from '../enums/HttpMethod';

options?: IRequestOptions;
data?: string | FormData;
data?: string | object | FormData;
method: HttpMethod;

@@ -13,2 +13,3 @@ collection?: PureCollection;

views?: Array<View>;
type?: IType | typeof PureModel;
}

@@ -5,2 +5,2 @@ import { IFetchOptions } from './IFetchOptions';

import { PureModel } from 'datx';
export declare type IInterceptor<T extends PureModel = PureModel> = (request: IFetchOptions, next: INetworkHandler) => Promise<Response<T>>;
export declare type IInterceptor<T extends PureModel = PureModel> = (request: IFetchOptions, next?: INetworkHandler) => Promise<Response<T>>;

@@ -1,11 +0,11 @@

import { PureCollection, IType, PureModel, IModelConstructor } from 'datx';
import { PureModel, PureCollection, IType } from 'datx';
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 | IModelConstructor<T>, id: string, options?: IRequestOptions): Promise<Response<T>>;
getMany<T extends INetworkModel = INetworkModel>(type: IType | IModelConstructor<T>, options?: IRequestOptions): Promise<Response<T>>;
request<T extends INetworkModel = INetworkModel>(url: string, method?: string, data?: object, options?: IRequestOptions): Promise<Response<T>>;
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: PureModel, options?: boolean | IRequestOptions): Promise<void>;
removeOne(model: INetworkModel, options?: boolean | IRequestOptions): Promise<void>;
}
import { IHeaders } from './IHeaders';
import { CachingStrategy } from '../enums/CachingStrategy';
export interface IRequestOptions {
query?: Array<{
key: string;
value: string;
} | string>;
query?: Record<string, string | Array<string> | object>;
cacheOptions?: {

@@ -9,0 +6,0 @@ cachingStrategy?: CachingStrategy;

import { IResponseHeaders } from './IResponseHeaders';
import { IHeaders } from './IHeaders';
import { PureCollection } from 'datx';
import { PureCollection, IType, PureModel } from 'datx';
export interface IResponseObject {

@@ -11,2 +11,3 @@ data?: object;

collection?: PureCollection;
type?: IType | typeof PureModel;
}

@@ -7,5 +7,9 @@ import { BaseRequest } from './BaseRequest';

import { ParamArrayType } from './enums/ParamArrayType';
import { PureCollection } from 'datx';
export declare function setUrl(url: string): (pipeline: BaseRequest) => void;
export declare function addInterceptor(interceptor: IInterceptor): (pipeline: BaseRequest) => void;
import { PureCollection, IType, PureModel } from 'datx';
import { IResponseObject } from './interfaces/IResponseObject';
import { IFetchOptions } from './interfaces/IFetchOptions';
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;

@@ -15,10 +19,12 @@ export declare function method(method: HttpMethod): (pipeline: BaseRequest) => void;

export declare function query(name: string, value: string | Array<string> | object): (pipeline: BaseRequest) => void;
export declare function query(params: Record<string, string | Array<string> | object>): (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 fetchReference(fetchReference: typeof fetch): (pipeline: BaseRequest) => void;
export declare function encodeQueryString(encodeQueryString: boolean): (pipeline: BaseRequest) => void;
export declare function paramArrayType(paramArrayType: ParamArrayType): (pipeline: BaseRequest) => void;
export declare function serializer(serialize: (data: object, _type: BodyType) => object): (pipeline: BaseRequest) => void;
export declare function parser(parse: (data: object) => object): (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;
import { PureModel, PureCollection, View } from 'datx';
import { IResponseHeaders } from './interfaces/IResponseHeaders';
import { IHeaders } from './interfaces/IHeaders';
import { IRequestOptions } from './interfaces/IRequestOptions';
import { IResponseSnapshot } from './interfaces/IResponseSnapshot';
import { IResponseObject } from './interfaces/IResponseObject';
export declare class Response<T extends PureModel> {
export declare class Response<T extends PureModel | Array<PureModel>> {
private __data;

@@ -47,4 +46,4 @@ private __internal;

get isSuccess(): boolean;
get data(): T | Array<T> | null;
constructor(response: IResponseObject, collection?: PureCollection, options?: IRequestOptions, overrideData?: T | Array<T>, views?: Array<View>);
get data(): T | null;
constructor(response: IResponseObject, collection?: PureCollection, overrideData?: T, views?: Array<View>);
private __updateInternal;

@@ -62,3 +61,3 @@ /**

get snapshot(): IResponseSnapshot;
update(response: IResponseObject, views?: Array<View>): Response<T>;
update(response: IResponseObject | Response<T>, views?: Array<View>): Response<T>;
}
{
"name": "datx-network",
"version": "2.0.0-beta.6",
"version": "2.0.0-beta.7",
"description": "DatX network layer",

@@ -5,0 +5,0 @@ "main": "dist/index.cjs.js",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc