├── .codeclimate.yml
├── .gitignore
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── dist
├── NetworkStore.d.ts
├── NetworkStore.js
├── NetworkUtils.d.ts
├── NetworkUtils.js
├── Record.d.ts
├── Record.js
├── Response.d.ts
├── Response.js
├── Store.d.ts
├── Store.js
├── enums
│ ├── ParamArrayType.d.ts
│ └── ParamArrayType.js
├── index.d.ts
├── index.js
├── interfaces
│ ├── ICache.d.ts
│ ├── ICache.js
│ ├── IDictionary.d.ts
│ ├── IDictionary.js
│ ├── IFilters.d.ts
│ ├── IFilters.js
│ ├── IHeaders.d.ts
│ ├── IHeaders.js
│ ├── IJsonApiIdentifier.d.ts
│ ├── IJsonApiIdentifier.js
│ ├── IJsonApiRecord.d.ts
│ ├── IJsonApiRecord.js
│ ├── IJsonApiRelationship.d.ts
│ ├── IJsonApiRelationship.js
│ ├── IJsonApiResponse.d.ts
│ ├── IJsonApiResponse.js
│ ├── IRawResponse.d.ts
│ ├── IRawResponse.js
│ ├── IRequestOptions.d.ts
│ ├── IRequestOptions.js
│ ├── IResponseHeaders.d.ts
│ ├── IResponseHeaders.js
│ ├── JsonApi.d.ts
│ └── JsonApi.js
├── utils.d.ts
└── utils.js
├── jsonapi.md
├── package-lock.json
├── package.json
├── src
├── NetworkStore.ts
├── NetworkUtils.ts
├── Record.ts
├── Response.ts
├── Store.ts
├── enums
│ └── ParamArrayType.ts
├── index.ts
├── interfaces
│ ├── ICache.ts
│ ├── IDictionary.ts
│ ├── IFilters.ts
│ ├── IHeaders.ts
│ ├── IRawResponse.ts
│ ├── IRequestOptions.ts
│ ├── IResponseHeaders.ts
│ └── JsonApi.ts
└── utils.ts
├── test
├── general.ts
├── issues.ts
├── main.ts
├── mocha.opts
├── mock
│ ├── error.json
│ ├── event-1.json
│ ├── event-1b.json
│ ├── event-1c.json
│ ├── event-1d.json
│ ├── events-1.json
│ ├── events-2.json
│ ├── image-1.json
│ ├── invalid.json
│ ├── issue-29.json
│ ├── issue-84a.json
│ ├── issue-84b.json
│ ├── issue-84c.json
│ ├── issue-84d.json
│ ├── issue-84e.json
│ ├── issue-falsy-meta-value.json
│ ├── jsonapi-object.json
│ ├── queue-1.json
│ └── session-1.json
├── network
│ ├── basics.ts
│ ├── caching.ts
│ ├── error-handling.ts
│ ├── headers.ts
│ ├── params.ts
│ └── updates.ts
└── utils
│ ├── api.ts
│ └── setup.ts
├── tsconfig.json
├── tslint.json
├── typings.json
└── typings
├── globals
└── isomorphic-fetch
│ ├── index.d.ts
│ └── typings.json
└── index.d.ts
/.codeclimate.yml:
--------------------------------------------------------------------------------
1 | engines:
2 | duplication:
3 | enabled: true
4 | config:
5 | languages:
6 | - javascript
7 | fixme:
8 | enabled: true
9 | ratings:
10 | paths:
11 | "**.ts"
12 | exclude_paths:
13 | - dist/
14 | - test/
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 |
6 | # Runtime data
7 | pids
8 | *.pid
9 | *.seed
10 |
11 | # Directory for instrumented libs generated by jscoverage/JSCover
12 | lib-cov
13 |
14 | # Coverage directory used by tools like istanbul
15 | coverage
16 |
17 | # nyc test coverage
18 | .nyc_output
19 |
20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
21 | .grunt
22 |
23 | # node-waf configuration
24 | .lock-wscript
25 |
26 | # Compiled binary addons (http://nodejs.org/api/addons.html)
27 | build/Release
28 |
29 | # Dependency directories
30 | node_modules
31 | jspm_packages
32 |
33 | # Optional npm cache directory
34 | .npm
35 |
36 | # Optional REPL history
37 | .node_repl_history
38 |
39 | *.map
40 | dist/test.*
41 |
42 | .DS_Store
43 |
44 | .vscode
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | src
2 | test
3 | .codeclimate.yml
4 | .travis.yml
5 | tsconfig.json
6 | tslint.json
7 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "6"
4 | - "8"
5 | - "10"
6 | install:
7 | - npm install
8 | script:
9 | - npm test
10 | after_success:
11 | - npm install -g codeclimate-test-reporter
12 | - codeclimate-test-reporter < coverage/lcov.info
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Infinum
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # mobx-jsonapi-store
2 |
3 | JSON API Store for MobX
4 |
5 | ## Deprecation and migration
6 |
7 | `mobx-jsonapi-store` and `mobx-collection-store` are deprecated in favor of [`datx`](https://github.com/infinum/datx) - it follows the same concepts, but adds support for MobX 4 and 5, better TypeScript support and more extensibility.
8 |
9 | If you're new to the libraries, check out the datx [examples](https://github.com/infinum/datx/tree/master/examples) and [docs](https://github.com/infinum/datx/wiki).
10 |
11 | If you already use `mobx-jsonapi-store`, check out the [migration guide](https://github.com/infinum/datx/wiki/Migration-from-mobx-jsonapi-store).
12 |
13 | -------
14 |
15 | Don't need any [JSON API](http://jsonapi.org/) specific features? Check out [mobx-collection-store](https://github.com/infinum/mobx-collection-store).
16 |
17 | **Can be used with [Redux DevTools](https://github.com/infinum/mobx-jsonapi-store/wiki/Redux-DevTools).**
18 |
19 | [](https://travis-ci.org/infinum/mobx-jsonapi-store)
20 | [](https://codeclimate.com/github/infinum/mobx-jsonapi-store/coverage)
21 | [](https://badge.fury.io/js/mobx-jsonapi-store)
22 |
23 | [](https://david-dm.org/infinum/mobx-jsonapi-store)
24 | [](https://david-dm.org/infinum/mobx-jsonapi-store#info=devDependencies)
25 | [](https://greenkeeper.io/)
26 |
27 | ## Basic example
28 |
29 | ```javascript
30 | import {Store} from 'mobx-jsonapi-store';
31 |
32 | const store = new Store();
33 | const user = store.sync(userResponse); // Assumption: userResponse was received from some API call and it's a valid JSON API response
34 | console.log(user.name); // "John"
35 | ```
36 |
37 | For more, check out the [Getting started](https://github.com/infinum/mobx-jsonapi-store/wiki/Getting-started) guide.
38 |
39 | ## Installation
40 |
41 | To install, use `npm` or `yarn`. The lib has a peer dependency of `mobx` 2.7.0 or later (including MobX 3) and `mobx-collection-store`.
42 |
43 | ```bash
44 | npm install mobx-jsonapi-store mobx-collection-store mobx --save
45 | ```
46 |
47 | ```bash
48 | yarn add mobx-jsonapi-store mobx-collection-store mobx
49 | ```
50 |
51 | Since the lib is exposed as a set of CommonJS modules, you'll need something like [webpack](https://webpack.js.org/) or browserify in order to use it in the browser.
52 |
53 | Don't forget to [prepare your code for production](https://webpack.js.org/guides/production/) for better performance!
54 |
55 | # Migration from v3 to v4
56 |
57 | Version 4 has a few breaking changes described in the [migration guide](https://github.com/infinum/mobx-jsonapi-store/wiki/Migrating-from-v3-to-v4).
58 |
59 | # Getting started
60 | The main idea behind the library is to have one instance of the store that contains multiple model types. This way, there can be references between models that can handle all use cases, including circular dependencies.
61 |
62 | * [Setting up networking](https://github.com/infinum/mobx-jsonapi-store/wiki/Networking)
63 | * [Defining models](https://github.com/infinum/mobx-jsonapi-store/wiki/Defining-models)
64 | * [References](https://github.com/infinum/mobx-jsonapi-store/wiki/References)
65 | * [Configuring the store](https://github.com/infinum/mobx-jsonapi-store/wiki/Configuring-the-store)
66 | * [Using the store](https://github.com/infinum/mobx-jsonapi-store/wiki/Using-the-store)
67 | * [Using the network methods](https://github.com/infinum/mobx-jsonapi-store/wiki/Using-the-network)
68 | * [Persisting data locally](https://github.com/infinum/mobx-jsonapi-store/wiki/Persisting-data-locally)
69 | * [Redux DevTools](https://github.com/infinum/mobx-jsonapi-store/wiki/Redux-DevTools)
70 |
71 | # JSON API Spec
72 | mobx-jsonapi-store is [100% compatible with the JSON API v1.0 spec](https://github.com/infinum/mobx-jsonapi-store/wiki/JSON-API-Spec)
73 |
74 | # API reference
75 |
76 | * [config](https://github.com/infinum/mobx-jsonapi-store/wiki/config)
77 | * [Store](https://github.com/infinum/mobx-jsonapi-store/wiki/Store)
78 | * [Record](https://github.com/infinum/mobx-jsonapi-store/wiki/Record)
79 | * [Response](https://github.com/infinum/mobx-jsonapi-store/wiki/Response)
80 | * [TypeScript interfaces](https://github.com/infinum/mobx-jsonapi-store/wiki/Interfaces)
81 |
82 | ## License
83 |
84 | The [MIT License](LICENSE)
85 |
86 | ## Credits
87 |
88 | mobx-jsonapi-store is maintained and sponsored by
89 | [Infinum](http://www.infinum.co).
90 |
91 |
92 |
--------------------------------------------------------------------------------
/dist/NetworkStore.d.ts:
--------------------------------------------------------------------------------
1 | import { Collection } from 'mobx-collection-store';
2 | import IHeaders from './interfaces/IHeaders';
3 | import IRequestOptions from './interfaces/IRequestOptions';
4 | import * as JsonApi from './interfaces/JsonApi';
5 | export declare class NetworkStore extends Collection {
6 | /**
7 | * Prepare the query params for the API call
8 | *
9 | * @protected
10 | * @param {string} type Record type
11 | * @param {(number|string)} [id] Record ID
12 | * @param {JsonApi.IRequest} [data] Request data
13 | * @param {IRequestOptions} [options] Server options
14 | * @returns {{
15 | * url: string,
16 | * data?: object,
17 | * headers: IHeaders,
18 | * }} Options needed for an API call
19 | *
20 | * @memberOf NetworkStore
21 | */
22 | protected __prepareQuery(type: string, id?: number | string, data?: JsonApi.IRequest, options?: IRequestOptions): {
23 | url: string;
24 | data?: object;
25 | headers: IHeaders;
26 | };
27 | }
28 |
--------------------------------------------------------------------------------
/dist/NetworkStore.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __extends = (this && this.__extends) || (function () {
3 | var extendStatics = function (d, b) {
4 | extendStatics = Object.setPrototypeOf ||
5 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7 | return extendStatics(d, b);
8 | };
9 | return function (d, b) {
10 | extendStatics(d, b);
11 | function __() { this.constructor = d; }
12 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13 | };
14 | })();
15 | Object.defineProperty(exports, "__esModule", { value: true });
16 | var mobx_collection_store_1 = require("mobx-collection-store");
17 | var NetworkUtils_1 = require("./NetworkUtils");
18 | var NetworkStore = /** @class */ (function (_super) {
19 | __extends(NetworkStore, _super);
20 | function NetworkStore() {
21 | return _super !== null && _super.apply(this, arguments) || this;
22 | }
23 | /**
24 | * Prepare the query params for the API call
25 | *
26 | * @protected
27 | * @param {string} type Record type
28 | * @param {(number|string)} [id] Record ID
29 | * @param {JsonApi.IRequest} [data] Request data
30 | * @param {IRequestOptions} [options] Server options
31 | * @returns {{
32 | * url: string,
33 | * data?: object,
34 | * headers: IHeaders,
35 | * }} Options needed for an API call
36 | *
37 | * @memberOf NetworkStore
38 | */
39 | NetworkStore.prototype.__prepareQuery = function (type, id, data, options) {
40 | var model = this.static.types.filter(function (item) { return item.type === type; })[0];
41 | var headers = (options ? options.headers : {}) || {};
42 | var url = NetworkUtils_1.buildUrl(type, id, model, options);
43 | return { data: data, headers: headers, url: url };
44 | };
45 | return NetworkStore;
46 | }(mobx_collection_store_1.Collection));
47 | exports.NetworkStore = NetworkStore;
48 |
--------------------------------------------------------------------------------
/dist/NetworkUtils.d.ts:
--------------------------------------------------------------------------------
1 | import { IModelConstructor } from 'mobx-collection-store';
2 | import ParamArrayType from './enums/ParamArrayType';
3 | import IDictionary from './interfaces/IDictionary';
4 | import IHeaders from './interfaces/IHeaders';
5 | import IRawResponse from './interfaces/IRawResponse';
6 | import IRequestOptions from './interfaces/IRequestOptions';
7 | import * as JsonApi from './interfaces/JsonApi';
8 | import { Record } from './Record';
9 | import { Response as LibResponse } from './Response';
10 | import { Store } from './Store';
11 | export declare type FetchType = (method: string, url: string, body?: object, requestHeaders?: IHeaders) => Promise;
12 | export interface IStoreFetchOpts {
13 | url: string;
14 | options?: IRequestOptions;
15 | data?: object;
16 | method: string;
17 | store: Store;
18 | }
19 | export declare type StoreFetchType = (options: IStoreFetchOpts) => Promise;
20 | export interface IConfigType {
21 | baseFetch: FetchType;
22 | baseUrl: string;
23 | defaultHeaders: IHeaders;
24 | defaultFetchOptions: IDictionary;
25 | fetchReference: Function;
26 | paramArrayType: ParamArrayType;
27 | storeFetch: StoreFetchType;
28 | transformRequest: (options: IStoreFetchOpts) => IStoreFetchOpts;
29 | transformResponse: (response: IRawResponse) => IRawResponse;
30 | }
31 | export declare const config: IConfigType;
32 | export declare function fetch(options: IStoreFetchOpts): Promise;
33 | /**
34 | * API call used to get data from the server
35 | *
36 | * @export
37 | * @param {Store} store Related Store
38 | * @param {string} url API call URL
39 | * @param {IHeaders} [headers] Headers to be sent
40 | * @param {IRequestOptions} [options] Server options
41 | * @returns {Promise} Resolves with a Response object
42 | */
43 | export declare function read(store: Store, url: string, headers?: IHeaders, options?: IRequestOptions): Promise;
44 | /**
45 | * API call used to create data on the server
46 | *
47 | * @export
48 | * @param {Store} store Related Store
49 | * @param {string} url API call URL
50 | * @param {object} [data] Request body
51 | * @param {IHeaders} [headers] Headers to be sent
52 | * @param {IRequestOptions} [options] Server options
53 | * @returns {Promise} Resolves with a Response object
54 | */
55 | export declare function create(store: Store, url: string, data?: object, headers?: IHeaders, options?: IRequestOptions): Promise;
56 | /**
57 | * API call used to update data on the server
58 | *
59 | * @export
60 | * @param {Store} store Related Store
61 | * @param {string} url API call URL
62 | * @param {object} [data] Request body
63 | * @param {IHeaders} [headers] Headers to be sent
64 | * @param {IRequestOptions} [options] Server options
65 | * @returns {Promise} Resolves with a Response object
66 | */
67 | export declare function update(store: Store, url: string, data?: object, headers?: IHeaders, options?: IRequestOptions): Promise;
68 | /**
69 | * API call used to remove data from the server
70 | *
71 | * @export
72 | * @param {Store} store Related Store
73 | * @param {string} url API call URL
74 | * @param {IHeaders} [headers] Headers to be sent
75 | * @param {IRequestOptions} [options] Server options
76 | * @returns {Promise} Resolves with a Response object
77 | */
78 | export declare function remove(store: Store, url: string, headers?: IHeaders, options?: IRequestOptions): Promise;
79 | /**
80 | * Fetch a link from the server
81 | *
82 | * @export
83 | * @param {JsonApi.ILink} link Link URL or a link object
84 | * @param {Store} store Store that will be used to save the response
85 | * @param {IDictionary} [requestHeaders] Request headers
86 | * @param {IRequestOptions} [options] Server options
87 | * @returns {Promise} Response promise
88 | */
89 | export declare function fetchLink(link: JsonApi.ILink, store: Store, requestHeaders?: IDictionary, options?: IRequestOptions): Promise;
90 | export declare function handleResponse(record: Record, prop?: string): (response: LibResponse) => Record;
91 | export declare function prefixUrl(url: any): string;
92 | export declare function buildUrl(type: number | string, id?: number | string, model?: IModelConstructor, options?: IRequestOptions): string;
93 |
--------------------------------------------------------------------------------
/dist/NetworkUtils.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __assign = (this && this.__assign) || function () {
3 | __assign = Object.assign || function(t) {
4 | for (var s, i = 1, n = arguments.length; i < n; i++) {
5 | s = arguments[i];
6 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 | t[p] = s[p];
8 | }
9 | return t;
10 | };
11 | return __assign.apply(this, arguments);
12 | };
13 | Object.defineProperty(exports, "__esModule", { value: true });
14 | var ParamArrayType_1 = require("./enums/ParamArrayType");
15 | var Response_1 = require("./Response");
16 | var utils_1 = require("./utils");
17 | exports.config = {
18 | /** Base URL for all API calls */
19 | baseUrl: '/',
20 | /** Default headers that will be sent to the server */
21 | defaultHeaders: {
22 | 'content-type': 'application/vnd.api+json',
23 | },
24 | /* Default options that will be passed to fetchReference */
25 | defaultFetchOptions: {},
26 | /** Reference of the fetch method that should be used */
27 | /* istanbul ignore next */
28 | fetchReference: utils_1.isBrowser && window.fetch && window.fetch.bind(window),
29 | /** Determines how will the request param arrays be stringified */
30 | paramArrayType: ParamArrayType_1.default.COMMA_SEPARATED,
31 | /**
32 | * Base implementation of the fetch function (can be overridden)
33 | *
34 | * @param {string} method API call method
35 | * @param {string} url API call URL
36 | * @param {object} [body] API call body
37 | * @param {IHeaders} [requestHeaders] Headers that will be sent
38 | * @returns {Promise} Resolves with a raw response object
39 | */
40 | baseFetch: function (method, url, body, requestHeaders) {
41 | var _this = this;
42 | var data;
43 | var status;
44 | var headers;
45 | var request = Promise.resolve();
46 | var uppercaseMethod = method.toUpperCase();
47 | var isBodySupported = uppercaseMethod !== 'GET' && uppercaseMethod !== 'HEAD';
48 | return request
49 | .then(function () {
50 | var reqHeaders = utils_1.assign({}, exports.config.defaultHeaders, requestHeaders);
51 | var options = utils_1.assign({}, exports.config.defaultFetchOptions, {
52 | body: isBodySupported && JSON.stringify(body) || undefined,
53 | headers: reqHeaders,
54 | method: method,
55 | });
56 | return _this.fetchReference(url, options);
57 | })
58 | .then(function (response) {
59 | status = response.status;
60 | headers = response.headers;
61 | return response.json();
62 | })
63 | .catch(function (e) {
64 | if (status === 204) {
65 | return null;
66 | }
67 | throw e;
68 | })
69 | .then(function (responseData) {
70 | data = responseData;
71 | if (status >= 400) {
72 | throw {
73 | message: "Invalid HTTP status: " + status,
74 | status: status,
75 | };
76 | }
77 | return { data: data, headers: headers, requestHeaders: requestHeaders, status: status };
78 | })
79 | .catch(function (error) {
80 | return { data: data, error: error, headers: headers, requestHeaders: requestHeaders, status: status };
81 | });
82 | },
83 | /**
84 | * Base implementation of the stateful fetch function (can be overridden)
85 | *
86 | * @param {IStoreFetchOpts} reqOptions API request options
87 | * @returns {Promise} Resolves with a response object
88 | */
89 | storeFetch: function (reqOptions) {
90 | var _a = exports.config.transformRequest(reqOptions), url = _a.url, options = _a.options, data = _a.data, _b = _a.method, method = _b === void 0 ? 'GET' : _b, store = _a.store;
91 | return exports.config.baseFetch(method, url, data, options && options.headers)
92 | .then(function (response) {
93 | var storeResponse = utils_1.assign(response, { store: store });
94 | return new Response_1.Response(exports.config.transformResponse(storeResponse), store, options);
95 | });
96 | },
97 | transformRequest: function (options) {
98 | return options;
99 | },
100 | transformResponse: function (response) {
101 | return response;
102 | },
103 | };
104 | function fetch(options) {
105 | return exports.config.storeFetch(options);
106 | }
107 | exports.fetch = fetch;
108 | /**
109 | * API call used to get data from the server
110 | *
111 | * @export
112 | * @param {Store} store Related Store
113 | * @param {string} url API call URL
114 | * @param {IHeaders} [headers] Headers to be sent
115 | * @param {IRequestOptions} [options] Server options
116 | * @returns {Promise} Resolves with a Response object
117 | */
118 | function read(store, url, headers, options) {
119 | return exports.config.storeFetch({
120 | data: null,
121 | method: 'GET',
122 | options: __assign({}, options, { headers: headers }),
123 | store: store,
124 | url: url,
125 | });
126 | }
127 | exports.read = read;
128 | /**
129 | * API call used to create data on the server
130 | *
131 | * @export
132 | * @param {Store} store Related Store
133 | * @param {string} url API call URL
134 | * @param {object} [data] Request body
135 | * @param {IHeaders} [headers] Headers to be sent
136 | * @param {IRequestOptions} [options] Server options
137 | * @returns {Promise} Resolves with a Response object
138 | */
139 | function create(store, url, data, headers, options) {
140 | return exports.config.storeFetch({
141 | data: data,
142 | method: 'POST',
143 | options: __assign({}, options, { headers: headers }),
144 | store: store,
145 | url: url,
146 | });
147 | }
148 | exports.create = create;
149 | /**
150 | * API call used to update data on the server
151 | *
152 | * @export
153 | * @param {Store} store Related Store
154 | * @param {string} url API call URL
155 | * @param {object} [data] Request body
156 | * @param {IHeaders} [headers] Headers to be sent
157 | * @param {IRequestOptions} [options] Server options
158 | * @returns {Promise} Resolves with a Response object
159 | */
160 | function update(store, url, data, headers, options) {
161 | return exports.config.storeFetch({
162 | data: data,
163 | method: 'PATCH',
164 | options: __assign({}, options, { headers: headers }),
165 | store: store,
166 | url: url,
167 | });
168 | }
169 | exports.update = update;
170 | /**
171 | * API call used to remove data from the server
172 | *
173 | * @export
174 | * @param {Store} store Related Store
175 | * @param {string} url API call URL
176 | * @param {IHeaders} [headers] Headers to be sent
177 | * @param {IRequestOptions} [options] Server options
178 | * @returns {Promise} Resolves with a Response object
179 | */
180 | function remove(store, url, headers, options) {
181 | return exports.config.storeFetch({
182 | data: null,
183 | method: 'DELETE',
184 | options: __assign({}, options, { headers: headers }),
185 | store: store,
186 | url: url,
187 | });
188 | }
189 | exports.remove = remove;
190 | /**
191 | * Fetch a link from the server
192 | *
193 | * @export
194 | * @param {JsonApi.ILink} link Link URL or a link object
195 | * @param {Store} store Store that will be used to save the response
196 | * @param {IDictionary} [requestHeaders] Request headers
197 | * @param {IRequestOptions} [options] Server options
198 | * @returns {Promise} Response promise
199 | */
200 | function fetchLink(link, store, requestHeaders, options) {
201 | if (link) {
202 | var href = typeof link === 'object' ? link.href : link;
203 | /* istanbul ignore else */
204 | if (href) {
205 | return read(store, href, requestHeaders, options);
206 | }
207 | }
208 | return Promise.resolve(new Response_1.Response({ data: null }, store));
209 | }
210 | exports.fetchLink = fetchLink;
211 | function handleResponse(record, prop) {
212 | return function (response) {
213 | /* istanbul ignore if */
214 | if (response.error) {
215 | throw response.error;
216 | }
217 | if (response.status === 204) {
218 | record['__persisted'] = true;
219 | return record;
220 | }
221 | else if (response.status === 202) {
222 | response.data.update({
223 | __prop__: prop,
224 | __queue__: true,
225 | __related__: record,
226 | });
227 | return response.data;
228 | }
229 | else {
230 | record['__persisted'] = true;
231 | return response.replaceData(record).data;
232 | }
233 | };
234 | }
235 | exports.handleResponse = handleResponse;
236 | function __prepareFilters(filters) {
237 | return __parametrize(filters).map(function (item) { return "filter[" + item.key + "]=" + item.value; });
238 | }
239 | function __prepareSort(sort) {
240 | return sort ? ["sort=" + sort] : [];
241 | }
242 | function __prepareIncludes(include) {
243 | return include ? ["include=" + include] : [];
244 | }
245 | function __prepareFields(fields) {
246 | var list = [];
247 | utils_1.objectForEach(fields, function (key) {
248 | list.push("fields[" + key + "]=" + fields[key]);
249 | });
250 | return list;
251 | }
252 | function __prepareRawParams(params) {
253 | return params.map(function (param) {
254 | if (typeof param === 'string') {
255 | return param;
256 | }
257 | return param.key + "=" + param.value;
258 | });
259 | }
260 | function prefixUrl(url) {
261 | return "" + exports.config.baseUrl + url;
262 | }
263 | exports.prefixUrl = prefixUrl;
264 | function __appendParams(url, params) {
265 | if (params.length) {
266 | url += '?' + params.join('&');
267 | }
268 | return url;
269 | }
270 | function __parametrize(params, scope) {
271 | if (scope === void 0) { scope = ''; }
272 | var list = [];
273 | utils_1.objectForEach(params, function (key) {
274 | if (params[key] instanceof Array) {
275 | if (exports.config.paramArrayType === ParamArrayType_1.default.OBJECT_PATH) {
276 | list.push.apply(list, __parametrize(params[key], key + "."));
277 | }
278 | else if (exports.config.paramArrayType === ParamArrayType_1.default.COMMA_SEPARATED) {
279 | list.push({ key: "" + scope + key, value: params[key].join(',') });
280 | }
281 | else if (exports.config.paramArrayType === ParamArrayType_1.default.MULTIPLE_PARAMS) {
282 | list.push.apply(list, params[key].map(function (param) { return ({ key: "" + scope + key, value: param }); }));
283 | }
284 | else if (exports.config.paramArrayType === ParamArrayType_1.default.PARAM_ARRAY) {
285 | list.push.apply(list, params[key].map(function (param) { return ({ key: "" + scope + key + "][", value: param }); }));
286 | }
287 | }
288 | else if (typeof params[key] === 'object') {
289 | list.push.apply(list, __parametrize(params[key], key + "."));
290 | }
291 | else {
292 | list.push({ key: "" + scope + key, value: params[key] });
293 | }
294 | });
295 | return list;
296 | }
297 | function buildUrl(type, id, model, options) {
298 | var path = model
299 | ? (utils_1.getValue(model['endpoint']) || model['baseUrl'] || model.type)
300 | : type;
301 | var url = id ? path + "/" + id : "" + path;
302 | var params = __prepareFilters((options && options.filter) || {}).concat(__prepareSort(options && options.sort), __prepareIncludes(options && options.include), __prepareFields((options && options.fields) || {}), __prepareRawParams((options && options.params) || []));
303 | return __appendParams(prefixUrl(url), params);
304 | }
305 | exports.buildUrl = buildUrl;
306 |
--------------------------------------------------------------------------------
/dist/Record.d.ts:
--------------------------------------------------------------------------------
1 | import { IModel, Model } from 'mobx-collection-store';
2 | import IDictionary from './interfaces/IDictionary';
3 | import IRequestOptions from './interfaces/IRequestOptions';
4 | import * as JsonApi from './interfaces/JsonApi';
5 | import { Response } from './Response';
6 | export declare class Record extends Model implements IModel {
7 | /**
8 | * Type property of the record class
9 | *
10 | * @static
11 | *
12 | * @memberOf Record
13 | */
14 | static typeAttribute: string[];
15 | /**
16 | * ID property of the record class
17 | *
18 | * @static
19 | *
20 | * @memberOf Record
21 | */
22 | static idAttribute: string[];
23 | /**
24 | * Should the autogenerated ID be sent to the server when creating a record
25 | *
26 | * @static
27 | * @type {boolean}
28 | * @memberOf Record
29 | */
30 | static useAutogeneratedIds: boolean;
31 | /**
32 | * Endpoint for API requests if there is no self link
33 | *
34 | * @static
35 | * @type {string|() => string}
36 | * @memberOf Record
37 | */
38 | static endpoint: string | (() => string);
39 | 'static': typeof Record;
40 | /**
41 | * Internal metadata
42 | *
43 | * @private
44 | * @type {IInternal}
45 | * @memberOf Record
46 | */
47 | private __internal;
48 | /**
49 | * Cache link fetch requests
50 | *
51 | * @private
52 | * @type {IDictionary>}
53 | * @memberOf Record
54 | */
55 | private __relationshipLinkCache;
56 | /**
57 | * Cache link fetch requests
58 | *
59 | * @private
60 | * @type {IDictionary>}
61 | * @memberOf Record
62 | */
63 | private __linkCache;
64 | /**
65 | * Get record relationship links
66 | *
67 | * @returns {IDictionary} Record relationship links
68 | *
69 | * @memberOf Record
70 | */
71 | getRelationshipLinks(): IDictionary;
72 | /**
73 | * Fetch a relationship link
74 | *
75 | * @param {string} relationship Name of the relationship
76 | * @param {string} name Name of the link
77 | * @param {IRequestOptions} [options] Server options
78 | * @param {boolean} [force=false] Ignore the existing cache
79 | * @returns {Promise} Response promise
80 | *
81 | * @memberOf Record
82 | */
83 | fetchRelationshipLink(relationship: string, name: string, options?: IRequestOptions, force?: boolean): Promise;
84 | /**
85 | * Get record metadata
86 | *
87 | * @returns {object} Record metadata
88 | *
89 | * @memberOf Record
90 | */
91 | getMeta(): object;
92 | /**
93 | * Get record links
94 | *
95 | * @returns {IDictionary} Record links
96 | *
97 | * @memberOf Record
98 | */
99 | getLinks(): IDictionary;
100 | /**
101 | * Fetch a record link
102 | *
103 | * @param {string} name Name of the link
104 | * @param {IRequestOptions} [options] Server options
105 | * @param {boolean} [force=false] Ignore the existing cache
106 | * @returns {Promise} Response promise
107 | *
108 | * @memberOf Record
109 | */
110 | fetchLink(name: string, options?: IRequestOptions, force?: boolean): Promise;
111 | /**
112 | * Get the persisted state
113 | *
114 | * @readonly
115 | * @private
116 | * @type {boolean}
117 | * @memberOf Record
118 | */
119 | /**
120 | * Set the persisted state
121 | *
122 | * @private
123 | *
124 | * @memberOf Record
125 | */
126 | private __persisted;
127 | /**
128 | * Serialize the record into JSON API format
129 | *
130 | * @returns {JsonApi.IRecord} JSON API formated record
131 | *
132 | * @memberOf Record
133 | */
134 | toJsonApi(): JsonApi.IRecord;
135 | /**
136 | * Saves (creates or updates) the record to the server
137 | *
138 | * @param {IRequestOptions} [options] Server options
139 | * @param {boolean} [ignoreSelf=false] Should the self link be ignored if it exists
140 | * @returns {Promise} Returns the record is successful or rejects with an error
141 | *
142 | * @memberOf Record
143 | */
144 | save(options?: IRequestOptions, ignoreSelf?: boolean): Promise;
145 | saveRelationship(relationship: string, options?: IRequestOptions): Promise;
146 | /**
147 | * Remove the records from the server and store
148 | *
149 | * @param {IRequestOptions} [options] Server options
150 | * @param {boolean} [ignoreSelf=false] Should the self link be ignored if it exists
151 | * @returns {Promise} Resolves true if successfull or rejects if there was an error
152 | *
153 | * @memberOf Record
154 | */
155 | remove(options?: IRequestOptions, ignoreSelf?: boolean): Promise;
156 | /**
157 | * Set the persisted status of the record
158 | *
159 | * @param {boolean} state Is the record persisted on the server
160 | *
161 | * @memberOf Record
162 | */
163 | setPersisted(state: boolean): void;
164 | /**
165 | * Get the persisted status of the record
166 | *
167 | * @memberOf Record
168 | */
169 | getPersisted(): boolean;
170 | /**
171 | * Get the URL that should be used for the API calls
172 | *
173 | * @private
174 | * @returns {string} API URL
175 | *
176 | * @memberOf Record
177 | */
178 | private __getUrl;
179 | }
180 |
--------------------------------------------------------------------------------
/dist/Record.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __extends = (this && this.__extends) || (function () {
3 | var extendStatics = function (d, b) {
4 | extendStatics = Object.setPrototypeOf ||
5 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7 | return extendStatics(d, b);
8 | };
9 | return function (d, b) {
10 | extendStatics(d, b);
11 | function __() { this.constructor = d; }
12 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13 | };
14 | })();
15 | Object.defineProperty(exports, "__esModule", { value: true });
16 | var mobx_collection_store_1 = require("mobx-collection-store");
17 | var NetworkUtils_1 = require("./NetworkUtils");
18 | var utils_1 = require("./utils");
19 | var Record = /** @class */ (function (_super) {
20 | __extends(Record, _super);
21 | function Record() {
22 | var _this = _super !== null && _super.apply(this, arguments) || this;
23 | /**
24 | * Cache link fetch requests
25 | *
26 | * @private
27 | * @type {IDictionary>}
28 | * @memberOf Record
29 | */
30 | _this.__relationshipLinkCache = {};
31 | /**
32 | * Cache link fetch requests
33 | *
34 | * @private
35 | * @type {IDictionary>}
36 | * @memberOf Record
37 | */
38 | _this.__linkCache = {};
39 | return _this;
40 | }
41 | /**
42 | * Get record relationship links
43 | *
44 | * @returns {IDictionary} Record relationship links
45 | *
46 | * @memberOf Record
47 | */
48 | Record.prototype.getRelationshipLinks = function () {
49 | return this.__internal && this.__internal.relationships;
50 | };
51 | /**
52 | * Fetch a relationship link
53 | *
54 | * @param {string} relationship Name of the relationship
55 | * @param {string} name Name of the link
56 | * @param {IRequestOptions} [options] Server options
57 | * @param {boolean} [force=false] Ignore the existing cache
58 | * @returns {Promise} Response promise
59 | *
60 | * @memberOf Record
61 | */
62 | Record.prototype.fetchRelationshipLink = function (relationship, name, options, force) {
63 | if (force === void 0) { force = false; }
64 | this.__relationshipLinkCache[relationship] = this.__relationshipLinkCache[relationship] || {};
65 | /* istanbul ignore else */
66 | if (!(name in this.__relationshipLinkCache) || force) {
67 | var link = ('relationships' in this.__internal &&
68 | relationship in this.__internal.relationships &&
69 | name in this.__internal.relationships[relationship]) ? this.__internal.relationships[relationship][name] : null;
70 | var headers = options && options.headers;
71 | this.__relationshipLinkCache[relationship][name] = NetworkUtils_1.fetchLink(link, this.__collection, headers, options);
72 | }
73 | return this.__relationshipLinkCache[relationship][name];
74 | };
75 | /**
76 | * Get record metadata
77 | *
78 | * @returns {object} Record metadata
79 | *
80 | * @memberOf Record
81 | */
82 | Record.prototype.getMeta = function () {
83 | return this.__internal && this.__internal.meta;
84 | };
85 | /**
86 | * Get record links
87 | *
88 | * @returns {IDictionary} Record links
89 | *
90 | * @memberOf Record
91 | */
92 | Record.prototype.getLinks = function () {
93 | return this.__internal && this.__internal.links;
94 | };
95 | /**
96 | * Fetch a record link
97 | *
98 | * @param {string} name Name of the link
99 | * @param {IRequestOptions} [options] Server options
100 | * @param {boolean} [force=false] Ignore the existing cache
101 | * @returns {Promise} Response promise
102 | *
103 | * @memberOf Record
104 | */
105 | Record.prototype.fetchLink = function (name, options, force) {
106 | var _this = this;
107 | if (force === void 0) { force = false; }
108 | if (!(name in this.__linkCache) || force) {
109 | var link = ('links' in this.__internal && name in this.__internal.links) ?
110 | this.__internal.links[name] : null;
111 | this.__linkCache[name] = NetworkUtils_1.fetchLink(link, this.__collection, options && options.headers, options);
112 | }
113 | var request = this.__linkCache[name];
114 | if (this['__queue__']) {
115 | request = this.__linkCache[name].then(function (response) {
116 | var related = _this['__related__'];
117 | var prop = _this['__prop__'];
118 | var record = response.data;
119 | if (record &&
120 | record.getRecordType() !== _this.getRecordType() &&
121 | record.getRecordType() === related.getRecordType()) {
122 | /* istanbul ignore if */
123 | if (prop) {
124 | related[prop] = record;
125 | return response;
126 | }
127 | related.__persisted = true;
128 | return response.replaceData(related);
129 | }
130 | return response;
131 | });
132 | }
133 | return request;
134 | };
135 | Object.defineProperty(Record.prototype, "__persisted", {
136 | /**
137 | * Get the persisted state
138 | *
139 | * @readonly
140 | * @private
141 | * @type {boolean}
142 | * @memberOf Record
143 | */
144 | get: function () {
145 | return (this.__internal && this.__internal.persisted) || false;
146 | },
147 | /**
148 | * Set the persisted state
149 | *
150 | * @private
151 | *
152 | * @memberOf Record
153 | */
154 | set: function (state) {
155 | this.__internal.persisted = state;
156 | },
157 | enumerable: true,
158 | configurable: true
159 | });
160 | /**
161 | * Serialize the record into JSON API format
162 | *
163 | * @returns {JsonApi.IRecord} JSON API formated record
164 | *
165 | * @memberOf Record
166 | */
167 | Record.prototype.toJsonApi = function () {
168 | var _this = this;
169 | var attributes = this.toJS();
170 | var useAutogenerated = this.static['useAutogeneratedIds'];
171 | var data = {
172 | attributes: attributes,
173 | id: (this.__persisted || useAutogenerated) ? this.getRecordId() : undefined,
174 | type: this.getRecordType(),
175 | };
176 | var refs = this['__refs'];
177 | utils_1.objectForEach(refs, function (key) {
178 | data.relationships = data.relationships || {};
179 | var rel = utils_1.mapItems(_this[key + "Id"], function (id) {
180 | if (!id && id !== 0) {
181 | return null;
182 | }
183 | return { id: id, type: refs[key] };
184 | });
185 | data.relationships[key] = { data: rel };
186 | delete data.attributes[key];
187 | delete data.attributes[key + "Id"];
188 | delete data.attributes[key + "Meta"];
189 | });
190 | delete data.attributes.__internal;
191 | delete data.attributes.__type__;
192 | return data;
193 | };
194 | /**
195 | * Saves (creates or updates) the record to the server
196 | *
197 | * @param {IRequestOptions} [options] Server options
198 | * @param {boolean} [ignoreSelf=false] Should the self link be ignored if it exists
199 | * @returns {Promise} Returns the record is successful or rejects with an error
200 | *
201 | * @memberOf Record
202 | */
203 | Record.prototype.save = function (options, ignoreSelf) {
204 | if (ignoreSelf === void 0) { ignoreSelf = false; }
205 | var store = this.__collection;
206 | var data = this.toJsonApi();
207 | var requestMethod = this.__persisted ? NetworkUtils_1.update : NetworkUtils_1.create;
208 | return requestMethod(store, this.__getUrl(options, ignoreSelf), { data: data }, options && options.headers)
209 | .then(NetworkUtils_1.handleResponse(this));
210 | };
211 | Record.prototype.saveRelationship = function (relationship, options) {
212 | var link = ('relationships' in this.__internal &&
213 | relationship in this.__internal.relationships &&
214 | 'self' in this.__internal.relationships[relationship]) ? this.__internal.relationships[relationship]['self'] : null;
215 | /* istanbul ignore if */
216 | if (!link) {
217 | throw new Error('The relationship doesn\'t have a defined link');
218 | }
219 | var store = this.__collection;
220 | /* istanbul ignore next */
221 | var href = typeof link === 'object' ? link.href : link;
222 | var type = this['__refs'][relationship];
223 | var data = utils_1.mapItems(this[relationship + "Id"], function (id) { return ({ id: id, type: type }); });
224 | return NetworkUtils_1.update(store, href, { data: data }, options && options.headers)
225 | .then(NetworkUtils_1.handleResponse(this, relationship));
226 | };
227 | /**
228 | * Remove the records from the server and store
229 | *
230 | * @param {IRequestOptions} [options] Server options
231 | * @param {boolean} [ignoreSelf=false] Should the self link be ignored if it exists
232 | * @returns {Promise} Resolves true if successfull or rejects if there was an error
233 | *
234 | * @memberOf Record
235 | */
236 | Record.prototype.remove = function (options, ignoreSelf) {
237 | var _this = this;
238 | if (ignoreSelf === void 0) { ignoreSelf = false; }
239 | var store = this.__collection;
240 | if (!this.__persisted) {
241 | this.__collection.remove(this.getRecordType(), this.getRecordId());
242 | return Promise.resolve(true);
243 | }
244 | return NetworkUtils_1.remove(store, this.__getUrl(options, ignoreSelf), options && options.headers)
245 | .then(function (response) {
246 | /* istanbul ignore if */
247 | if (response.error) {
248 | throw response.error;
249 | }
250 | _this.__persisted = false;
251 | if (_this.__collection) {
252 | _this.__collection.remove(_this.getRecordType(), _this.getRecordId());
253 | }
254 | return true;
255 | });
256 | };
257 | /**
258 | * Set the persisted status of the record
259 | *
260 | * @param {boolean} state Is the record persisted on the server
261 | *
262 | * @memberOf Record
263 | */
264 | Record.prototype.setPersisted = function (state) {
265 | this.__persisted = state;
266 | };
267 | /**
268 | * Get the persisted status of the record
269 | *
270 | * @memberOf Record
271 | */
272 | Record.prototype.getPersisted = function () {
273 | return this.__persisted;
274 | };
275 | /**
276 | * Get the URL that should be used for the API calls
277 | *
278 | * @private
279 | * @returns {string} API URL
280 | *
281 | * @memberOf Record
282 | */
283 | Record.prototype.__getUrl = function (options, ignoreSelf) {
284 | var links = this.getLinks();
285 | if (!ignoreSelf && links && links.self) {
286 | var self_1 = links.self;
287 | /* istanbul ignore next */
288 | return typeof self_1 === 'string' ? self_1 : self_1.href;
289 | }
290 | /* istanbul ignore next */
291 | var type = utils_1.getValue(this.static.endpoint) || this.getRecordType() || this.static.type;
292 | return NetworkUtils_1.buildUrl(type, this.__persisted ? this.getRecordId() : null, null, options);
293 | };
294 | /**
295 | * Type property of the record class
296 | *
297 | * @static
298 | *
299 | * @memberOf Record
300 | */
301 | Record.typeAttribute = ['__internal', 'type'];
302 | /**
303 | * ID property of the record class
304 | *
305 | * @static
306 | *
307 | * @memberOf Record
308 | */
309 | Record.idAttribute = ['__internal', 'id'];
310 | /**
311 | * Should the autogenerated ID be sent to the server when creating a record
312 | *
313 | * @static
314 | * @type {boolean}
315 | * @memberOf Record
316 | */
317 | Record.useAutogeneratedIds = false;
318 | return Record;
319 | }(mobx_collection_store_1.Model));
320 | exports.Record = Record;
321 |
--------------------------------------------------------------------------------
/dist/Response.d.ts:
--------------------------------------------------------------------------------
1 | import { IModel } from 'mobx-collection-store';
2 | import IDictionary from './interfaces/IDictionary';
3 | import IHeaders from './interfaces/IHeaders';
4 | import IRawResponse from './interfaces/IRawResponse';
5 | import IRequestOptions from './interfaces/IRequestOptions';
6 | import IResponseHeaders from './interfaces/IResponseHeaders';
7 | import * as JsonApi from './interfaces/JsonApi';
8 | import { Record } from './Record';
9 | import { Store } from './Store';
10 | export declare class Response {
11 | /**
12 | * API response data (synced with the store)
13 | *
14 | * @type {(IModel|Array)}
15 | * @memberOf Response
16 | */
17 | data?: IModel | Array;
18 | /**
19 | * API response metadata
20 | *
21 | * @type {object}
22 | * @memberOf Response
23 | */
24 | meta?: object;
25 | /**
26 | * API reslonse links
27 | *
28 | * @type {object}
29 | * @memberOf Response
30 | */
31 | links?: IDictionary;
32 | /**
33 | * The JSON API object returned by the server
34 | *
35 | * @type {JsonApi.IJsonApiObject}
36 | * @memberOf Response
37 | */
38 | jsonapi?: JsonApi.IJsonApiObject;
39 | /**
40 | * Headers received from the API call
41 | *
42 | * @type {IResponseHeaders}
43 | * @memberOf Response
44 | */
45 | headers?: IResponseHeaders;
46 | /**
47 | * Headers sent to the server
48 | *
49 | * @type {IHeaders}
50 | * @memberOf Response
51 | */
52 | requestHeaders?: IHeaders;
53 | /**
54 | * Request error
55 | *
56 | * @type {(Array|Error)}
57 | * @memberOf Response
58 | */
59 | error?: Array | Error;
60 | /**
61 | * First data page
62 | *
63 | * @type {Promise}
64 | * @memberOf Response
65 | */
66 | first: Promise;
67 | /**
68 | * Previous data page
69 | *
70 | * @type {Promise}
71 | * @memberOf Response
72 | */
73 | prev: Promise;
74 | /**
75 | * Next data page
76 | *
77 | * @type {Promise}
78 | * @memberOf Response
79 | */
80 | next: Promise;
81 | /**
82 | * Last data page
83 | *
84 | * @type {Promise}
85 | * @memberOf Response
86 | */
87 | last: Promise;
88 | /**
89 | * Received HTTP status
90 | *
91 | * @type {number}
92 | * @memberOf Response
93 | */
94 | status: number;
95 | /**
96 | * Related Store
97 | *
98 | * @private
99 | * @type {Store}
100 | * @memberOf Response
101 | */
102 | private __store;
103 | /**
104 | * Server options
105 | *
106 | * @private
107 | * @type {IRequestOptions}
108 | * @memberOf Response
109 | */
110 | private __options;
111 | /**
112 | * Original server response
113 | *
114 | * @private
115 | * @type {IRawResponse}
116 | * @memberOf Response
117 | */
118 | private __response;
119 | /**
120 | * Cache used for the link requests
121 | *
122 | * @private
123 | * @type {IDictionary>}
124 | * @memberOf Response
125 | */
126 | private __cache;
127 | constructor(response: IRawResponse, store?: Store, options?: IRequestOptions, overrideData?: IModel | Array);
128 | /**
129 | * Replace the response record with a different record. Used to replace a record while keeping the same reference
130 | *
131 | * @param {IModel} data New data
132 | * @returns {Response}
133 | *
134 | * @memberOf Response
135 | */
136 | replaceData(data: Record): Response;
137 | /**
138 | * Update references in the store
139 | *
140 | * @private
141 | * @param {any} type Record type
142 | * @param {any} oldId Old redord ID
143 | * @param {any} newId New record ID
144 | * @memberof Response
145 | */
146 | private __updateStoreReferences;
147 | /**
148 | * Update models that reference the updated model
149 | *
150 | * @private
151 | * @param {any} oldId Old record ID
152 | * @param {any} newId new record ID
153 | * @memberof Response
154 | */
155 | private __updateReferences;
156 | /**
157 | * Function called when a link is beeing fetched. The returned value is cached
158 | *
159 | * @private
160 | * @param {any} name Link name
161 | * @returns Promise that resolves with a Response object
162 | *
163 | * @memberOf Response
164 | */
165 | private __fetchLink;
166 | }
167 |
--------------------------------------------------------------------------------
/dist/Response.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6 | return c > 3 && r && Object.defineProperty(target, key, r), r;
7 | };
8 | Object.defineProperty(exports, "__esModule", { value: true });
9 | var mobx_1 = require("mobx");
10 | var Record_1 = require("./Record");
11 | var utils_1 = require("./utils");
12 | var NetworkUtils_1 = require("./NetworkUtils");
13 | var Response = /** @class */ (function () {
14 | function Response(response, store, options, overrideData) {
15 | var _this = this;
16 | /**
17 | * Cache used for the link requests
18 | *
19 | * @private
20 | * @type {IDictionary>}
21 | * @memberOf Response
22 | */
23 | this.__cache = {};
24 | this.__store = store;
25 | this.__options = options;
26 | this.__response = response;
27 | this.status = response.status;
28 | if (store) {
29 | this.data = overrideData ? store.add(overrideData) : store.sync(response.data);
30 | }
31 | else if (response.data) {
32 | // The case when a record is not in a store and save/remove are used
33 | var resp = response.data;
34 | /* istanbul ignore if */
35 | if (resp.data instanceof Array) {
36 | throw new Error('A save/remove operation should not return an array of results');
37 | }
38 | this.data = overrideData || new Record_1.Record(utils_1.flattenRecord(resp.data));
39 | }
40 | this.meta = (response.data && response.data.meta) || {};
41 | this.links = (response.data && response.data.links) || {};
42 | this.jsonapi = (response.data && response.data.jsonapi) || {};
43 | this.headers = response.headers;
44 | this.requestHeaders = response.requestHeaders;
45 | this.error = (response.data && response.data.errors) || response.error;
46 | var linkGetter = {};
47 | Object.keys(this.links).forEach(function (link) {
48 | linkGetter[link] = mobx_1.computed(function () { return _this.__fetchLink(link); });
49 | });
50 | mobx_1.extendObservable(this, linkGetter);
51 | Object.freeze(this);
52 | if (this.error) {
53 | throw this;
54 | }
55 | }
56 | /**
57 | * Replace the response record with a different record. Used to replace a record while keeping the same reference
58 | *
59 | * @param {IModel} data New data
60 | * @returns {Response}
61 | *
62 | * @memberOf Response
63 | */
64 | Response.prototype.replaceData = function (data) {
65 | var record = this.data;
66 | if (record === data) {
67 | return this;
68 | }
69 | var oldId = data.getRecordId();
70 | var newId = record.getRecordId();
71 | var type = record.getRecordType();
72 | if (this.__store) {
73 | this.__store.remove(type, newId);
74 | }
75 | data.update(record.toJS());
76 | // TODO: Refactor this to avoid using mobx-collection-store internals
77 | data['__internal'].id = newId;
78 | this.__updateStoreReferences(type, oldId, newId);
79 | return new Response(this.__response, this.__store, this.__options, data);
80 | };
81 | /**
82 | * Update references in the store
83 | *
84 | * @private
85 | * @param {any} type Record type
86 | * @param {any} oldId Old redord ID
87 | * @param {any} newId New record ID
88 | * @memberof Response
89 | */
90 | Response.prototype.__updateStoreReferences = function (type, oldId, newId) {
91 | if (this.__store) {
92 | var modelHash = this.__store['__modelHash'][type];
93 | var oldModel = modelHash[oldId];
94 | modelHash[newId] = oldModel;
95 | delete modelHash[oldId];
96 | this.__updateReferences(type, oldId, newId);
97 | }
98 | };
99 | /**
100 | * Update models that reference the updated model
101 | *
102 | * @private
103 | * @param {any} oldId Old record ID
104 | * @param {any} newId new record ID
105 | * @memberof Response
106 | */
107 | Response.prototype.__updateReferences = function (type, oldId, newId) {
108 | this.__store['__data'].map(function (model) {
109 | var keyList = utils_1.keys(model['__data']);
110 | keyList.map(function (key) {
111 | var keyId = key + "Id";
112 | var refs = model.__refs || model.static.refs;
113 | var refsType = refs && refs[key];
114 | if (key in model && keyId in model && refsType === type) {
115 | if (mobx_1.isObservableArray(model[keyId])) {
116 | var index = model[keyId].indexOf(oldId);
117 | if (index > -1) {
118 | model[keyId][index] = newId;
119 | }
120 | }
121 | else if (model[keyId] === oldId) {
122 | model[keyId] = newId;
123 | }
124 | }
125 | });
126 | });
127 | };
128 | /**
129 | * Function called when a link is beeing fetched. The returned value is cached
130 | *
131 | * @private
132 | * @param {any} name Link name
133 | * @returns Promise that resolves with a Response object
134 | *
135 | * @memberOf Response
136 | */
137 | Response.prototype.__fetchLink = function (name) {
138 | if (!this.__cache[name]) {
139 | /* istanbul ignore next */
140 | var link = name in this.links ? this.links[name] : null;
141 | this.__cache[name] = NetworkUtils_1.fetchLink(link, this.__store, this.requestHeaders, this.__options);
142 | }
143 | return this.__cache[name];
144 | };
145 | __decorate([
146 | mobx_1.action
147 | ], Response.prototype, "replaceData", null);
148 | return Response;
149 | }());
150 | exports.Response = Response;
151 |
--------------------------------------------------------------------------------
/dist/Store.d.ts:
--------------------------------------------------------------------------------
1 | import { IModel } from 'mobx-collection-store';
2 | import IRequestOptions from './interfaces/IRequestOptions';
3 | import * as JsonApi from './interfaces/JsonApi';
4 | import { NetworkStore } from './NetworkStore';
5 | import { Record } from './Record';
6 | import { Response } from './Response';
7 | export declare class Store extends NetworkStore {
8 | /**
9 | * List of Models that will be used in the collection
10 | *
11 | * @static
12 | *
13 | * @memberOf Store
14 | */
15 | static types: (typeof Record)[];
16 | /**
17 | * Should the cache be used for API calls when possible
18 | *
19 | * @static
20 | *
21 | * @memberof Store
22 | */
23 | static cache: boolean;
24 | static: typeof Store;
25 | /**
26 | * Cache async actions (can be overriden with force=true)
27 | *
28 | * @private
29 | *
30 | * @memberOf Store
31 | */
32 | private __cache;
33 | /**
34 | * Import the JSON API data into the store
35 | *
36 | * @param {IJsonApiResponse} body - JSON API response
37 | * @returns {(IModel|Array)} - Models parsed from body.data
38 | *
39 | * @memberOf Store
40 | */
41 | sync(body: JsonApi.IResponse): IModel | Array;
42 | /**
43 | * Fetch the records with the given type and id
44 | *
45 | * @param {string} type Record type
46 | * @param {number|string} type Record id
47 | * @param {boolean} [force] Force fetch (currently not used)
48 | * @param {IRequestOptions} [options] Server options
49 | * @returns {Promise} Resolves with the Response object or rejects with an error
50 | *
51 | * @memberOf Store
52 | */
53 | fetch(type: string, id: number | string, force?: boolean, options?: IRequestOptions): Promise;
54 | /**
55 | * Fetch the first page of records of the given type
56 | *
57 | * @param {string} type Record type
58 | * @param {boolean} [force] Force fetch (currently not used)
59 | * @param {IRequestOptions} [options] Server options
60 | * @returns {Promise} Resolves with the Response object or rejects with an error
61 | *
62 | * @memberOf Store
63 | */
64 | fetchAll(type: string, force?: boolean, options?: IRequestOptions): Promise;
65 | /**
66 | * Destroy a record (API & store)
67 | *
68 | * @param {string} type Record type
69 | * @param {(number|string)} id Record id
70 | * @param {IRequestOptions} [options] Server options
71 | * @returns {Promise} Resolves true or rejects with an error
72 | *
73 | * @memberOf Store
74 | */
75 | destroy(type: string, id: number | string, options?: IRequestOptions): Promise;
76 | reset(): void;
77 | request(url: string, method?: string, data?: object, options?: IRequestOptions): Promise;
78 | removeAll(type: string): Array;
79 | /**
80 | * Make the request and handle the errors
81 | *
82 | * @param {IQueryParams} query Request query info
83 | * @param {IRequestOptions} [options] Server options
84 | * @returns {Promise} Resolves with the Response object or rejects with an error
85 | *
86 | * @memberof Store
87 | */
88 | private __doFetch;
89 | /**
90 | * Function used to handle response errors
91 | *
92 | * @private
93 | * @param {Response} response API response
94 | * @returns API response
95 | *
96 | * @memberOf Store
97 | */
98 | private __handleErrors;
99 | /**
100 | * Add a new JSON API record to the store
101 | *
102 | * @private
103 | * @param {IJsonApiRecord} obj - Object to be added
104 | * @returns {IModel}
105 | *
106 | * @memberOf Store
107 | */
108 | private __addRecord;
109 | /**
110 | * Update the relationships between models
111 | *
112 | * @private
113 | * @param {IJsonApiRecord} obj - Object to be updated
114 | * @returns {void}
115 | *
116 | * @memberOf Store
117 | */
118 | private __updateRelationships;
119 | /**
120 | * Iterate trough JSON API response models
121 | *
122 | * @private
123 | * @param {IJsonApiResponse} body - JSON API response
124 | * @param {Function} fn - Function to call for every instance
125 | * @returns
126 | *
127 | * @memberOf Store
128 | */
129 | private __iterateEntries;
130 | }
131 |
--------------------------------------------------------------------------------
/dist/Store.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __extends = (this && this.__extends) || (function () {
3 | var extendStatics = function (d, b) {
4 | extendStatics = Object.setPrototypeOf ||
5 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7 | return extendStatics(d, b);
8 | };
9 | return function (d, b) {
10 | extendStatics(d, b);
11 | function __() { this.constructor = d; }
12 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13 | };
14 | })();
15 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
16 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
18 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19 | return c > 3 && r && Object.defineProperty(target, key, r), r;
20 | };
21 | Object.defineProperty(exports, "__esModule", { value: true });
22 | var mobx_1 = require("mobx");
23 | var NetworkStore_1 = require("./NetworkStore");
24 | var NetworkUtils_1 = require("./NetworkUtils");
25 | var Record_1 = require("./Record");
26 | var utils_1 = require("./utils");
27 | var Store = /** @class */ (function (_super) {
28 | __extends(Store, _super);
29 | function Store() {
30 | var _this = _super !== null && _super.apply(this, arguments) || this;
31 | /**
32 | * Cache async actions (can be overriden with force=true)
33 | *
34 | * @private
35 | *
36 | * @memberOf Store
37 | */
38 | _this.__cache = {
39 | fetch: {},
40 | fetchAll: {},
41 | };
42 | return _this;
43 | }
44 | /**
45 | * Import the JSON API data into the store
46 | *
47 | * @param {IJsonApiResponse} body - JSON API response
48 | * @returns {(IModel|Array)} - Models parsed from body.data
49 | *
50 | * @memberOf Store
51 | */
52 | Store.prototype.sync = function (body) {
53 | var data = this.__iterateEntries(body, this.__addRecord.bind(this));
54 | this.__iterateEntries(body, this.__updateRelationships.bind(this));
55 | return data;
56 | };
57 | /**
58 | * Fetch the records with the given type and id
59 | *
60 | * @param {string} type Record type
61 | * @param {number|string} type Record id
62 | * @param {boolean} [force] Force fetch (currently not used)
63 | * @param {IRequestOptions} [options] Server options
64 | * @returns {Promise} Resolves with the Response object or rejects with an error
65 | *
66 | * @memberOf Store
67 | */
68 | Store.prototype.fetch = function (type, id, force, options) {
69 | var _this = this;
70 | var query = this.__prepareQuery(type, id, null, options);
71 | if (!this.static.cache) {
72 | return this.__doFetch(query, options);
73 | }
74 | this.__cache.fetch[type] = this.__cache.fetch[type] || {};
75 | // TODO: Should we fake the cache if the record already exists?
76 | if (force || !(query.url in this.__cache.fetch[type])) {
77 | this.__cache.fetch[type][query.url] = this.__doFetch(query, options)
78 | .catch(function (e) {
79 | // Don't cache if there was an error
80 | delete _this.__cache.fetch[type][query.url];
81 | throw e;
82 | });
83 | }
84 | return this.__cache.fetch[type][query.url];
85 | };
86 | /**
87 | * Fetch the first page of records of the given type
88 | *
89 | * @param {string} type Record type
90 | * @param {boolean} [force] Force fetch (currently not used)
91 | * @param {IRequestOptions} [options] Server options
92 | * @returns {Promise} Resolves with the Response object or rejects with an error
93 | *
94 | * @memberOf Store
95 | */
96 | Store.prototype.fetchAll = function (type, force, options) {
97 | var _this = this;
98 | var query = this.__prepareQuery(type, null, null, options);
99 | if (!this.static.cache) {
100 | return this.__doFetch(query, options);
101 | }
102 | this.__cache.fetchAll[type] = this.__cache.fetchAll[type] || {};
103 | if (force || !(query.url in this.__cache.fetchAll[type])) {
104 | this.__cache.fetchAll[type][query.url] = this.__doFetch(query, options)
105 | .catch(function (e) {
106 | // Don't cache if there was an error
107 | delete _this.__cache.fetchAll[type][query.url];
108 | throw e;
109 | });
110 | }
111 | return this.__cache.fetchAll[type][query.url];
112 | };
113 | /**
114 | * Destroy a record (API & store)
115 | *
116 | * @param {string} type Record type
117 | * @param {(number|string)} id Record id
118 | * @param {IRequestOptions} [options] Server options
119 | * @returns {Promise} Resolves true or rejects with an error
120 | *
121 | * @memberOf Store
122 | */
123 | Store.prototype.destroy = function (type, id, options) {
124 | var model = this.find(type, id);
125 | if (model) {
126 | return model.remove(options);
127 | }
128 | return Promise.resolve(true);
129 | };
130 | Store.prototype.reset = function () {
131 | _super.prototype.reset.call(this);
132 | this.__cache.fetch = {};
133 | this.__cache.fetchAll = {};
134 | };
135 | Store.prototype.request = function (url, method, data, options) {
136 | if (method === void 0) { method = 'GET'; }
137 | return NetworkUtils_1.fetch({ url: NetworkUtils_1.prefixUrl(url), options: options, data: data, method: method, store: this });
138 | };
139 | Store.prototype.removeAll = function (type) {
140 | var models = _super.prototype.removeAll.call(this, type);
141 | this.__cache.fetch[type] = {};
142 | this.__cache.fetchAll[type] = {};
143 | return models;
144 | };
145 | /**
146 | * Make the request and handle the errors
147 | *
148 | * @param {IQueryParams} query Request query info
149 | * @param {IRequestOptions} [options] Server options
150 | * @returns {Promise} Resolves with the Response object or rejects with an error
151 | *
152 | * @memberof Store
153 | */
154 | Store.prototype.__doFetch = function (query, options) {
155 | return NetworkUtils_1.read(this, query.url, query.headers, options).then(this.__handleErrors);
156 | };
157 | /**
158 | * Function used to handle response errors
159 | *
160 | * @private
161 | * @param {Response} response API response
162 | * @returns API response
163 | *
164 | * @memberOf Store
165 | */
166 | Store.prototype.__handleErrors = function (response) {
167 | /* istanbul ignore if */
168 | if (response.error) {
169 | throw response.error;
170 | }
171 | return response;
172 | };
173 | /**
174 | * Add a new JSON API record to the store
175 | *
176 | * @private
177 | * @param {IJsonApiRecord} obj - Object to be added
178 | * @returns {IModel}
179 | *
180 | * @memberOf Store
181 | */
182 | Store.prototype.__addRecord = function (obj) {
183 | var type = obj.type, id = obj.id;
184 | var record = this.find(type, id);
185 | var flattened = utils_1.flattenRecord(obj);
186 | if (record) {
187 | record.update(flattened);
188 | }
189 | else if (this.static.types.filter(function (item) { return item.type === obj.type; }).length) {
190 | record = this.add(flattened, obj.type);
191 | }
192 | else {
193 | record = new Record_1.Record(flattened);
194 | this.add(record);
195 | }
196 | // In case a record is not a real record
197 | // TODO: Figure out when this happens and try to handle it better
198 | /* istanbul ignore else */
199 | if (record && typeof record.setPersisted === 'function') {
200 | record.setPersisted(true);
201 | }
202 | return record;
203 | };
204 | /**
205 | * Update the relationships between models
206 | *
207 | * @private
208 | * @param {IJsonApiRecord} obj - Object to be updated
209 | * @returns {void}
210 | *
211 | * @memberOf Store
212 | */
213 | Store.prototype.__updateRelationships = function (obj) {
214 | var _this = this;
215 | var record = this.find(obj.type, obj.id);
216 | var refs = obj.relationships ? Object.keys(obj.relationships) : [];
217 | refs.forEach(function (ref) {
218 | if (!('data' in obj.relationships[ref])) {
219 | return;
220 | }
221 | var items = obj.relationships[ref].data;
222 | if (items instanceof Array && items.length < 1) {
223 | if (!(ref in record) || ref in record['__data']) { // Hack to check if it's not a back ref
224 | record.assignRef(ref, []);
225 | }
226 | }
227 | else if (record) {
228 | if (items) {
229 | var models = utils_1.mapItems(items, function (_a) {
230 | var id = _a.id, type = _a.type;
231 | return _this.find(type, id) || id;
232 | });
233 | var itemType = items instanceof Array ? items[0].type : items.type;
234 | record.assignRef(ref, models, itemType);
235 | }
236 | else {
237 | record.assignRef(ref, null);
238 | }
239 | }
240 | });
241 | };
242 | /**
243 | * Iterate trough JSON API response models
244 | *
245 | * @private
246 | * @param {IJsonApiResponse} body - JSON API response
247 | * @param {Function} fn - Function to call for every instance
248 | * @returns
249 | *
250 | * @memberOf Store
251 | */
252 | Store.prototype.__iterateEntries = function (body, fn) {
253 | utils_1.mapItems((body && body.included) || [], fn);
254 | return utils_1.mapItems((body && body.data) || [], fn);
255 | };
256 | /**
257 | * List of Models that will be used in the collection
258 | *
259 | * @static
260 | *
261 | * @memberOf Store
262 | */
263 | Store.types = [Record_1.Record];
264 | /**
265 | * Should the cache be used for API calls when possible
266 | *
267 | * @static
268 | *
269 | * @memberof Store
270 | */
271 | Store.cache = true;
272 | __decorate([
273 | mobx_1.action
274 | ], Store.prototype, "sync", null);
275 | return Store;
276 | }(NetworkStore_1.NetworkStore));
277 | exports.Store = Store;
278 |
--------------------------------------------------------------------------------
/dist/enums/ParamArrayType.d.ts:
--------------------------------------------------------------------------------
1 | declare enum ParamArrayType {
2 | MULTIPLE_PARAMS = 0,
3 | COMMA_SEPARATED = 1,
4 | PARAM_ARRAY = 2,
5 | OBJECT_PATH = 3
6 | }
7 | export default ParamArrayType;
8 |
--------------------------------------------------------------------------------
/dist/enums/ParamArrayType.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 | var ParamArrayType;
4 | (function (ParamArrayType) {
5 | ParamArrayType[ParamArrayType["MULTIPLE_PARAMS"] = 0] = "MULTIPLE_PARAMS";
6 | ParamArrayType[ParamArrayType["COMMA_SEPARATED"] = 1] = "COMMA_SEPARATED";
7 | ParamArrayType[ParamArrayType["PARAM_ARRAY"] = 2] = "PARAM_ARRAY";
8 | ParamArrayType[ParamArrayType["OBJECT_PATH"] = 3] = "OBJECT_PATH";
9 | })(ParamArrayType || (ParamArrayType = {}));
10 | exports.default = ParamArrayType;
11 |
--------------------------------------------------------------------------------
/dist/index.d.ts:
--------------------------------------------------------------------------------
1 | import * as JsonApi from './interfaces/JsonApi';
2 | export { JsonApi };
3 | export { Store } from './Store';
4 | export { Record } from './Record';
5 | export { Response } from './Response';
6 | export * from './NetworkUtils';
7 | export { default as ICache } from './interfaces/ICache';
8 | export { default as IDictionary } from './interfaces/IDictionary';
9 | export { default as IFilters } from './interfaces/IFilters';
10 | export { default as IHeaders } from './interfaces/IHeaders';
11 | export { default as IRawResponse } from './interfaces/IRawResponse';
12 | export { default as IRequestOptions } from './interfaces/IRequestOptions';
13 | export { default as IResponseHeaders } from './interfaces/IResponseHeaders';
14 | export { default as ParamArrayType } from './enums/ParamArrayType';
15 | export { ICollection, IModel, IModelConstructor, IReferences } from 'mobx-collection-store';
16 |
--------------------------------------------------------------------------------
/dist/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | function __export(m) {
3 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4 | }
5 | Object.defineProperty(exports, "__esModule", { value: true });
6 | var JsonApi = require("./interfaces/JsonApi");
7 | exports.JsonApi = JsonApi;
8 | var Store_1 = require("./Store");
9 | exports.Store = Store_1.Store;
10 | var Record_1 = require("./Record");
11 | exports.Record = Record_1.Record;
12 | var Response_1 = require("./Response");
13 | exports.Response = Response_1.Response;
14 | __export(require("./NetworkUtils"));
15 | var ParamArrayType_1 = require("./enums/ParamArrayType");
16 | exports.ParamArrayType = ParamArrayType_1.default;
17 |
--------------------------------------------------------------------------------
/dist/interfaces/ICache.d.ts:
--------------------------------------------------------------------------------
1 | import IDictionary from './IDictionary';
2 | import { Response } from '../Response';
3 | interface ICache {
4 | fetchAll: IDictionary>>;
5 | fetch: IDictionary>>;
6 | }
7 | export default ICache;
8 |
--------------------------------------------------------------------------------
/dist/interfaces/ICache.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/interfaces/IDictionary.d.ts:
--------------------------------------------------------------------------------
1 | interface IDictionary {
2 | [key: string]: T;
3 | }
4 | export default IDictionary;
5 |
--------------------------------------------------------------------------------
/dist/interfaces/IDictionary.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/interfaces/IFilters.d.ts:
--------------------------------------------------------------------------------
1 | interface IFilters {
2 | [key: string]: number | string | Array | Array | IFilters;
3 | }
4 | export default IFilters;
5 |
--------------------------------------------------------------------------------
/dist/interfaces/IFilters.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/interfaces/IHeaders.d.ts:
--------------------------------------------------------------------------------
1 | import IDictionary from './IDictionary';
2 | declare type IHeaders = IDictionary;
3 | export default IHeaders;
4 |
--------------------------------------------------------------------------------
/dist/interfaces/IHeaders.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiIdentifier.d.ts:
--------------------------------------------------------------------------------
1 | interface IJsonApiIdentifier {
2 | id: number | string;
3 | type: string;
4 | }
5 | export default IJsonApiIdentifier;
6 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiIdentifier.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiRecord.d.ts:
--------------------------------------------------------------------------------
1 | import IDictionary from './IDictionary';
2 | import IJsonApiRelationship from './IJsonApiRelationship';
3 | interface IJsonApiRecord {
4 | id: number | string;
5 | type: string;
6 | attributes: IDictionary;
7 | relationships?: IDictionary;
8 | }
9 | export default IJsonApiRecord;
10 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiRecord.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiRelationship.d.ts:
--------------------------------------------------------------------------------
1 | import IDictionary from './IDictionary';
2 | import IJsonApiIdentifier from './IJsonApiIdentifier';
3 | interface IJsonApiRelationship {
4 | data?: IJsonApiIdentifier | Array;
5 | links?: IDictionary;
6 | }
7 | export default IJsonApiRelationship;
8 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiRelationship.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiResponse.d.ts:
--------------------------------------------------------------------------------
1 | import IJsonApiRecord from './IJsonApiRecord';
2 | interface IJsonApiResponse {
3 | data: IJsonApiRecord | Array;
4 | included?: Array;
5 | }
6 | export default IJsonApiResponse;
7 |
--------------------------------------------------------------------------------
/dist/interfaces/IJsonApiResponse.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
--------------------------------------------------------------------------------
/dist/interfaces/IRawResponse.d.ts:
--------------------------------------------------------------------------------
1 | import { Store } from '../Store';
2 | import IHeaders from './IHeaders';
3 | import IResponseHeaders from './IResponseHeaders';
4 | import * as JsonApi from './JsonApi';
5 | interface IRawResponse {
6 | data?: JsonApi.IResponse;
7 | error?: Error;
8 | headers?: IResponseHeaders;
9 | requestHeaders?: IHeaders;
10 | status?: number;
11 | jsonapi?: JsonApi.IJsonApiObject;
12 | store?: Store;
13 | }
14 | export default IRawResponse;
15 |
--------------------------------------------------------------------------------
/dist/interfaces/IRawResponse.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/interfaces/IRequestOptions.d.ts:
--------------------------------------------------------------------------------
1 | import IDictionary from './IDictionary';
2 | import IFilters from './IFilters';
3 | import IHeaders from './IHeaders';
4 | interface IRequestOptions {
5 | headers?: IHeaders;
6 | include?: string | Array;
7 | filter?: IFilters;
8 | sort?: string | Array;
9 | fields?: IDictionary>;
10 | params?: Array<{
11 | key: string;
12 | value: string;
13 | } | string>;
14 | }
15 | export default IRequestOptions;
16 |
--------------------------------------------------------------------------------
/dist/interfaces/IRequestOptions.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/interfaces/IResponseHeaders.d.ts:
--------------------------------------------------------------------------------
1 | interface IResponseHeaders {
2 | get(name: string): string;
3 | }
4 | export default IResponseHeaders;
5 |
--------------------------------------------------------------------------------
/dist/interfaces/IResponseHeaders.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/interfaces/JsonApi.d.ts:
--------------------------------------------------------------------------------
1 | import IDictionary from './IDictionary';
2 | interface IIdentifier {
3 | id?: number | string;
4 | type: string;
5 | }
6 | interface IJsonApiObject {
7 | version?: string;
8 | meta?: IDictionary;
9 | }
10 | declare type ILink = string | {
11 | href: string;
12 | meta: IDictionary;
13 | };
14 | interface IError {
15 | id?: string | number;
16 | links?: {
17 | about: ILink;
18 | };
19 | status?: number;
20 | code?: string;
21 | title?: string;
22 | detail?: string;
23 | source?: {
24 | pointer?: string;
25 | parameter?: string;
26 | };
27 | meta?: IDictionary;
28 | }
29 | interface IRelationship {
30 | data?: IIdentifier | Array;
31 | links?: IDictionary;
32 | meta?: IDictionary;
33 | }
34 | interface IRecord extends IIdentifier {
35 | attributes: IDictionary;
36 | relationships?: IDictionary;
37 | links?: IDictionary;
38 | meta?: IDictionary;
39 | }
40 | interface IResponse {
41 | data?: IRecord | Array;
42 | errors?: Array;
43 | included?: Array;
44 | meta?: IDictionary;
45 | links?: IDictionary;
46 | jsonapi?: IJsonApiObject;
47 | }
48 | declare type IRequest = IResponse;
49 | export { IIdentifier, IJsonApiObject, ILink, IError, IRelationship, IRecord, IResponse, IRequest, };
50 |
--------------------------------------------------------------------------------
/dist/interfaces/JsonApi.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 |
--------------------------------------------------------------------------------
/dist/utils.d.ts:
--------------------------------------------------------------------------------
1 | import IDictionary from './interfaces/IDictionary';
2 | import * as JsonApi from './interfaces/JsonApi';
3 | /**
4 | * Iterate trough object keys
5 | *
6 | * @param {object} obj - Object that needs to be iterated
7 | * @param {Function} fn - Function that should be called for every iteration
8 | */
9 | export declare function objectForEach(obj: object, fn: Function): void;
10 | /**
11 | * Iterate trough one item or array of items and call the defined function
12 | *
13 | * @export
14 | * @template T
15 | * @param {(object|Array