@ember-data-mirror/request-utils 5.4.0-alpha.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +11 -0
- package/README.md +66 -0
- package/addon/index.js +620 -0
- package/addon/index.js.map +1 -0
- package/addon-main.js +19 -0
- package/package.json +81 -0
- package/unstable-preview-types/index.d.ts +472 -0
- package/unstable-preview-types/index.d.ts.map +1 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (C) 2017-2023 Ember.js contributors
|
|
4
|
+
Portions Copyright (C) 2011-2017 Tilde, Inc. and contributors.
|
|
5
|
+
Portions Copyright (C) 2011 LivingSocial Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
8
|
+
|
|
9
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img
|
|
3
|
+
class="project-logo"
|
|
4
|
+
src="./ember-data-logo-dark.svg#gh-dark-mode-only"
|
|
5
|
+
alt="EmberData RequestUtils"
|
|
6
|
+
width="240px"
|
|
7
|
+
title="EmberData RequestUtils"
|
|
8
|
+
/>
|
|
9
|
+
<img
|
|
10
|
+
class="project-logo"
|
|
11
|
+
src="./ember-data-logo-light.svg#gh-light-mode-only"
|
|
12
|
+
alt="EmberData RequestUtils"
|
|
13
|
+
width="240px"
|
|
14
|
+
title="EmberData RequestUtils"
|
|
15
|
+
/>
|
|
16
|
+
</p>
|
|
17
|
+
|
|
18
|
+
<p align="center">Utilities for Requests</p>
|
|
19
|
+
|
|
20
|
+
This package provides Simple utility function to assist in url building, query params, and other common request operations.
|
|
21
|
+
|
|
22
|
+
It's built for [*Ember***Data**](https://github.com/emberjs/data/) but useful more broadly if you're looking for lightweight functions to assist in working with urls and query params.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
|
|
27
|
+
|
|
28
|
+
```no-highlight
|
|
29
|
+
pnpm add @ember-data-mirror/request-utils
|
|
30
|
+
```
|
|
31
|
+
## Utils
|
|
32
|
+
|
|
33
|
+
- [buildBaseUrl]()
|
|
34
|
+
- [sortQueryParams]()
|
|
35
|
+
- [buildQueryParams]()
|
|
36
|
+
- [filterEmpty]()
|
|
37
|
+
|
|
38
|
+
### As a Library Primitive
|
|
39
|
+
|
|
40
|
+
These primitives may be used directly or composed by request builders to provide a consistent interface for building requests.
|
|
41
|
+
|
|
42
|
+
For instance:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { buildBaseURL, buildQueryParams } from '@ember-data-mirror/request-utils';
|
|
46
|
+
|
|
47
|
+
const baseURL = buildBaseURL({
|
|
48
|
+
host: 'https://api.example.com',
|
|
49
|
+
namespace: 'api/v1',
|
|
50
|
+
resourcePath: 'emberDevelopers',
|
|
51
|
+
op: 'query',
|
|
52
|
+
identifier: { type: 'ember-developer' }
|
|
53
|
+
});
|
|
54
|
+
const url = `${baseURL}?${buildQueryParams({ name: 'Chris', include:['pets'] })}`;
|
|
55
|
+
// => 'https://api.example.com/api/v1/emberDevelopers?include=pets&name=Chris'
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
This is useful, but not as useful as the REST request builder for query which is sugar over this (and more!):
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { query } from '@ember-data-mirror/rest/request';
|
|
62
|
+
|
|
63
|
+
const options = query('ember-developer', { name: 'Chris', include:['pets'] });
|
|
64
|
+
// => { url: 'https://api.example.com/api/v1/emberDevelopers?include=pets&name=Chris' }
|
|
65
|
+
// Note: options will also include other request options like headers, method, etc.
|
|
66
|
+
```
|
package/addon/index.js
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
import { assert, deprecate } from '@ember/debug';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Simple utility function to assist in url building,
|
|
5
|
+
* query params, and other common request operations.
|
|
6
|
+
*
|
|
7
|
+
* These primitives may be used directly or composed
|
|
8
|
+
* by request builders to provide a consistent interface
|
|
9
|
+
* for building requests.
|
|
10
|
+
*
|
|
11
|
+
* For instance:
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { buildBaseURL, buildQueryParams } from '@ember-data-mirror/request-utils';
|
|
15
|
+
*
|
|
16
|
+
* const baseURL = buildBaseURL({
|
|
17
|
+
* host: 'https://api.example.com',
|
|
18
|
+
* namespace: 'api/v1',
|
|
19
|
+
* resourcePath: 'emberDevelopers',
|
|
20
|
+
* op: 'query',
|
|
21
|
+
* identifier: { type: 'ember-developer' }
|
|
22
|
+
* });
|
|
23
|
+
* const url = `${baseURL}?${buildQueryParams({ name: 'Chris', include:['pets'] })}`;
|
|
24
|
+
* // => 'https://api.example.com/api/v1/emberDevelopers?include=pets&name=Chris'
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* This is useful, but not as useful as the REST request builder for query which is sugar
|
|
28
|
+
* over this (and more!):
|
|
29
|
+
*
|
|
30
|
+
* ```ts
|
|
31
|
+
* import { query } from '@ember-data-mirror/rest/request';
|
|
32
|
+
*
|
|
33
|
+
* const options = query('ember-developer', { name: 'Chris', include:['pets'] });
|
|
34
|
+
* // => { url: 'https://api.example.com/api/v1/emberDevelopers?include=pets&name=Chris' }
|
|
35
|
+
* // Note: options will also include other request options like headers, method, etc.
|
|
36
|
+
* ```
|
|
37
|
+
*
|
|
38
|
+
* @module @ember-data-mirror/request-utils
|
|
39
|
+
* @main @ember-data-mirror/request-utils
|
|
40
|
+
* @public
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
// prevents the final constructed object from needing to add
|
|
44
|
+
// host and namespace which are provided by the final consuming
|
|
45
|
+
// class to the prototype which can result in overwrite errors
|
|
46
|
+
|
|
47
|
+
const CONFIG = {
|
|
48
|
+
host: '',
|
|
49
|
+
namespace: ''
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Sets the global configuration for `buildBaseURL`
|
|
54
|
+
* for host and namespace values for the application.
|
|
55
|
+
*
|
|
56
|
+
* These values may still be overridden by passing
|
|
57
|
+
* them to buildBaseURL directly.
|
|
58
|
+
*
|
|
59
|
+
* This method may be called as many times as needed.
|
|
60
|
+
* host values of `''` or `'/'` are equivalent.
|
|
61
|
+
*
|
|
62
|
+
* Except for the value of `/` as host, host should not
|
|
63
|
+
* end with `/`.
|
|
64
|
+
*
|
|
65
|
+
* namespace should not start or end with a `/`.
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* type BuildURLConfig = {
|
|
69
|
+
* host: string;
|
|
70
|
+
* namespace: string'
|
|
71
|
+
* }
|
|
72
|
+
* ```
|
|
73
|
+
*
|
|
74
|
+
* Example:
|
|
75
|
+
*
|
|
76
|
+
* ```ts
|
|
77
|
+
* import { setBuildURLConfig } from '@ember-data-mirror/request-utils';
|
|
78
|
+
*
|
|
79
|
+
* setBuildURLConfig({
|
|
80
|
+
* host: 'https://api.example.com',
|
|
81
|
+
* namespace: 'api/v1'
|
|
82
|
+
* });
|
|
83
|
+
* ```
|
|
84
|
+
*
|
|
85
|
+
* @method setBuildURLConfig
|
|
86
|
+
* @static
|
|
87
|
+
* @public
|
|
88
|
+
* @for @ember-data-mirror/request-utils
|
|
89
|
+
* @param {BuildURLConfig} config
|
|
90
|
+
* @return void
|
|
91
|
+
*/
|
|
92
|
+
function setBuildURLConfig(config) {
|
|
93
|
+
assert(`setBuildURLConfig: You must pass a config object`, config);
|
|
94
|
+
assert(`setBuildURLConfig: You must pass a config object with a 'host' or 'namespace' property`, 'host' in config || 'namespace' in config);
|
|
95
|
+
CONFIG.host = config.host || '';
|
|
96
|
+
CONFIG.namespace = config.namespace || '';
|
|
97
|
+
assert(`buildBaseURL: host must NOT end with '/', received '${CONFIG.host}'`, CONFIG.host === '/' || !CONFIG.host.endsWith('/'));
|
|
98
|
+
assert(`buildBaseURL: namespace must NOT start with '/', received '${CONFIG.namespace}'`, !CONFIG.namespace.startsWith('/'));
|
|
99
|
+
assert(`buildBaseURL: namespace must NOT end with '/', received '${CONFIG.namespace}'`, !CONFIG.namespace.endsWith('/'));
|
|
100
|
+
}
|
|
101
|
+
const OPERATIONS_WITH_PRIMARY_RECORDS = new Set(['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord']);
|
|
102
|
+
function isOperationWithPrimaryRecord(options) {
|
|
103
|
+
return 'op' in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
|
|
104
|
+
}
|
|
105
|
+
function hasResourcePath(options) {
|
|
106
|
+
return 'resourcePath' in options && typeof options.resourcePath === 'string' && options.resourcePath.length > 0;
|
|
107
|
+
}
|
|
108
|
+
function resourcePathForType(options) {
|
|
109
|
+
assert(`resourcePathForType: You must pass a valid op as part of options`, 'op' in options && typeof options.op === 'string');
|
|
110
|
+
return options.op === 'findMany' ? options.identifiers[0].type : options.identifier.type;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Builds a URL for a request based on the provided options.
|
|
115
|
+
* Does not include support for building query params (see `buildQueryParams`)
|
|
116
|
+
* so that it may be composed cleanly with other query-params strategies.
|
|
117
|
+
*
|
|
118
|
+
* Usage:
|
|
119
|
+
*
|
|
120
|
+
* ```ts
|
|
121
|
+
* import { buildBaseURL } from '@ember-data-mirror/request-utils';
|
|
122
|
+
*
|
|
123
|
+
* const url = buildBaseURL({
|
|
124
|
+
* host: 'https://api.example.com',
|
|
125
|
+
* namespace: 'api/v1',
|
|
126
|
+
* resourcePath: 'emberDevelopers',
|
|
127
|
+
* op: 'query',
|
|
128
|
+
* identifier: { type: 'ember-developer' }
|
|
129
|
+
* });
|
|
130
|
+
*
|
|
131
|
+
* // => 'https://api.example.com/api/v1/emberDevelopers'
|
|
132
|
+
* ```
|
|
133
|
+
*
|
|
134
|
+
* On the surface this may seem like a lot of work to do something simple, but
|
|
135
|
+
* it is designed to be composable with other utilities and interfaces that the
|
|
136
|
+
* average product engineer will never need to see or use.
|
|
137
|
+
*
|
|
138
|
+
* A few notes:
|
|
139
|
+
*
|
|
140
|
+
* - `resourcePath` is optional, but if it is not provided, `identifier.type` will be used.
|
|
141
|
+
* - `host` and `namespace` are optional, but if they are not provided, the values globally
|
|
142
|
+
* configured via `setBuildURLConfig` will be used.
|
|
143
|
+
* - `op` is required and must be one of the following:
|
|
144
|
+
* - 'findRecord' 'query' 'findMany' 'findRelatedCollection' 'findRelatedRecord'` 'createRecord' 'updateRecord' 'deleteRecord'
|
|
145
|
+
* - Depending on the value of `op`, `identifier` or `identifiers` will be required.
|
|
146
|
+
*
|
|
147
|
+
* @method buildBaseURL
|
|
148
|
+
* @static
|
|
149
|
+
* @public
|
|
150
|
+
* @for @ember-data-mirror/request-utils
|
|
151
|
+
* @param urlOptions
|
|
152
|
+
* @return string
|
|
153
|
+
*/
|
|
154
|
+
function buildBaseURL(urlOptions) {
|
|
155
|
+
const options = Object.assign({
|
|
156
|
+
host: CONFIG.host,
|
|
157
|
+
namespace: CONFIG.namespace
|
|
158
|
+
}, urlOptions);
|
|
159
|
+
assert(`buildBaseURL: You must pass \`op\` as part of options`, hasResourcePath(options) || typeof options.op === 'string' && options.op.length > 0);
|
|
160
|
+
assert(`buildBaseURL: You must pass \`identifier\` as part of options`, hasResourcePath(options) || options.op === 'findMany' || options.identifier && typeof options.identifier === 'object');
|
|
161
|
+
assert(`buildBaseURL: You must pass \`identifiers\` as part of options`, hasResourcePath(options) || options.op !== 'findMany' || options.identifiers && Array.isArray(options.identifiers) && options.identifiers.length > 0 && options.identifiers.every(i => i && typeof i === 'object'));
|
|
162
|
+
assert(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'id'`, hasResourcePath(options) || !isOperationWithPrimaryRecord(options) || typeof options.identifier.id === 'string' && options.identifier.id.length > 0);
|
|
163
|
+
assert(`buildBaseURL: You must pass \`identifiers\` as part of options`, hasResourcePath(options) || options.op !== 'findMany' || options.identifiers.every(i => typeof i.id === 'string' && i.id.length > 0));
|
|
164
|
+
assert(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'type'`, hasResourcePath(options) || options.op === 'findMany' || typeof options.identifier.type === 'string' && options.identifier.type.length > 0);
|
|
165
|
+
assert(`buildBaseURL: You must pass valid \`identifiers\` as part of options, expected 'type'`, hasResourcePath(options) || options.op !== 'findMany' || typeof options.identifiers[0].type === 'string' && options.identifiers[0].type.length > 0);
|
|
166
|
+
|
|
167
|
+
// prettier-ignore
|
|
168
|
+
const idPath = isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id) : '';
|
|
169
|
+
const resourcePath = options.resourcePath || resourcePathForType(options);
|
|
170
|
+
const {
|
|
171
|
+
host,
|
|
172
|
+
namespace
|
|
173
|
+
} = options;
|
|
174
|
+
const fieldPath = 'fieldPath' in options ? options.fieldPath : '';
|
|
175
|
+
assert(`buildBaseURL: You tried to build a url for a ${String('op' in options ? options.op + ' ' : '')}request to ${resourcePath} but resourcePath must be set or op must be one of "${['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord', 'createRecord', 'query', 'findMany'].join('","')}".`, hasResourcePath(options) || ['findRecord', 'query', 'findMany', 'findRelatedCollection', 'findRelatedRecord', 'createRecord', 'updateRecord', 'deleteRecord'].includes(options.op));
|
|
176
|
+
assert(`buildBaseURL: host must NOT end with '/', received '${host}'`, host === '/' || !host.endsWith('/'));
|
|
177
|
+
assert(`buildBaseURL: namespace must NOT start with '/', received '${namespace}'`, !namespace.startsWith('/'));
|
|
178
|
+
assert(`buildBaseURL: namespace must NOT end with '/', received '${namespace}'`, !namespace.endsWith('/'));
|
|
179
|
+
assert(`buildBaseURL: resourcePath must NOT start with '/', received '${resourcePath}'`, !resourcePath.startsWith('/'));
|
|
180
|
+
assert(`buildBaseURL: resourcePath must NOT end with '/', received '${resourcePath}'`, !resourcePath.endsWith('/'));
|
|
181
|
+
assert(`buildBaseURL: fieldPath must NOT start with '/', received '${fieldPath}'`, !fieldPath.startsWith('/'));
|
|
182
|
+
assert(`buildBaseURL: fieldPath must NOT end with '/', received '${fieldPath}'`, !fieldPath.endsWith('/'));
|
|
183
|
+
assert(`buildBaseURL: idPath must NOT start with '/', received '${idPath}'`, !idPath.startsWith('/'));
|
|
184
|
+
assert(`buildBaseURL: idPath must NOT end with '/', received '${idPath}'`, !idPath.endsWith('/'));
|
|
185
|
+
const hasHost = host !== '' && host !== '/';
|
|
186
|
+
const url = [hasHost ? host : '', namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');
|
|
187
|
+
return hasHost ? url : `/${url}`;
|
|
188
|
+
}
|
|
189
|
+
const DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS = {
|
|
190
|
+
arrayFormat: 'comma'
|
|
191
|
+
};
|
|
192
|
+
function handleInclude(include) {
|
|
193
|
+
assert(`Expected include to be a string or array, got ${typeof include}`, typeof include === 'string' || Array.isArray(include));
|
|
194
|
+
return typeof include === 'string' ? include.split(',') : include;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* filter out keys of an object that have falsy values or point to empty arrays
|
|
199
|
+
* returning a new object with only those keys that have truthy values / non-empty arrays
|
|
200
|
+
*
|
|
201
|
+
* @method filterEmpty
|
|
202
|
+
* @static
|
|
203
|
+
* @public
|
|
204
|
+
* @for @ember-data-mirror/request-utils
|
|
205
|
+
* @param {Record<string, Serializable>} source object to filter keys with empty values from
|
|
206
|
+
* @return {Record<string, Serializable>} A new object with the keys that contained empty values removed
|
|
207
|
+
*/
|
|
208
|
+
function filterEmpty(source) {
|
|
209
|
+
const result = {};
|
|
210
|
+
for (const key in source) {
|
|
211
|
+
const value = source[key];
|
|
212
|
+
// Allow `0` and `false` but filter falsy values that indicate "empty"
|
|
213
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
214
|
+
if (!Array.isArray(value) || value.length > 0) {
|
|
215
|
+
result[key] = source[key];
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return result;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Sorts query params by both key and value returning a new URLSearchParams
|
|
224
|
+
* object with the keys inserted in sorted order.
|
|
225
|
+
*
|
|
226
|
+
* Treats `included` specially, splicing it into an array if it is a string and sorting the array.
|
|
227
|
+
*
|
|
228
|
+
* Options:
|
|
229
|
+
* - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
|
|
230
|
+
*
|
|
231
|
+
* 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`
|
|
232
|
+
* 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`
|
|
233
|
+
* 'repeat': appends the key for every value e.g. `&ids=1&ids=2`
|
|
234
|
+
* 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`
|
|
235
|
+
*
|
|
236
|
+
* @method sortQueryParams
|
|
237
|
+
* @static
|
|
238
|
+
* @public
|
|
239
|
+
* @for @ember-data-mirror/request-utils
|
|
240
|
+
* @param {URLSearchParams | object} params
|
|
241
|
+
* @param {object} options
|
|
242
|
+
* @return {URLSearchParams} A URLSearchParams with keys inserted in sorted order
|
|
243
|
+
*/
|
|
244
|
+
function sortQueryParams(params, options) {
|
|
245
|
+
const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
|
|
246
|
+
const paramsIsObject = !(params instanceof URLSearchParams);
|
|
247
|
+
const urlParams = new URLSearchParams();
|
|
248
|
+
const dictionaryParams = paramsIsObject ? params : {};
|
|
249
|
+
if (!paramsIsObject) {
|
|
250
|
+
params.forEach((value, key) => {
|
|
251
|
+
const hasExisting = (key in dictionaryParams);
|
|
252
|
+
if (!hasExisting) {
|
|
253
|
+
dictionaryParams[key] = value;
|
|
254
|
+
} else {
|
|
255
|
+
const existingValue = dictionaryParams[key];
|
|
256
|
+
if (Array.isArray(existingValue)) {
|
|
257
|
+
existingValue.push(value);
|
|
258
|
+
} else {
|
|
259
|
+
dictionaryParams[key] = [existingValue, value];
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
if ('include' in dictionaryParams) {
|
|
265
|
+
dictionaryParams.include = handleInclude(dictionaryParams.include);
|
|
266
|
+
}
|
|
267
|
+
const sortedKeys = Object.keys(dictionaryParams).sort();
|
|
268
|
+
sortedKeys.forEach(key => {
|
|
269
|
+
const value = dictionaryParams[key];
|
|
270
|
+
if (Array.isArray(value)) {
|
|
271
|
+
value.sort();
|
|
272
|
+
switch (opts.arrayFormat) {
|
|
273
|
+
case 'indices':
|
|
274
|
+
value.forEach((v, i) => {
|
|
275
|
+
urlParams.append(`${key}[${i}]`, String(v));
|
|
276
|
+
});
|
|
277
|
+
return;
|
|
278
|
+
case 'bracket':
|
|
279
|
+
value.forEach(v => {
|
|
280
|
+
urlParams.append(`${key}[]`, String(v));
|
|
281
|
+
});
|
|
282
|
+
return;
|
|
283
|
+
case 'repeat':
|
|
284
|
+
value.forEach(v => {
|
|
285
|
+
urlParams.append(key, String(v));
|
|
286
|
+
});
|
|
287
|
+
return;
|
|
288
|
+
case 'comma':
|
|
289
|
+
default:
|
|
290
|
+
urlParams.append(key, value.join(','));
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
} else {
|
|
294
|
+
urlParams.append(key, String(value));
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
return urlParams;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Sorts query params by both key and value, returning a query params string
|
|
302
|
+
*
|
|
303
|
+
* Treats `included` specially, splicing it into an array if it is a string and sorting the array.
|
|
304
|
+
*
|
|
305
|
+
* Options:
|
|
306
|
+
* - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
|
|
307
|
+
*
|
|
308
|
+
* 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`
|
|
309
|
+
* 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`
|
|
310
|
+
* 'repeat': appends the key for every value e.g. `ids=1&ids=2`
|
|
311
|
+
* 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`
|
|
312
|
+
*
|
|
313
|
+
* @method buildQueryParams
|
|
314
|
+
* @static
|
|
315
|
+
* @public
|
|
316
|
+
* @for @ember-data-mirror/request-utils
|
|
317
|
+
* @param {URLSearchParams | object} params
|
|
318
|
+
* @param {object} [options]
|
|
319
|
+
* @return {string} A sorted query params string without the leading `?`
|
|
320
|
+
*/
|
|
321
|
+
function buildQueryParams(params, options) {
|
|
322
|
+
return sortQueryParams(params, options).toString();
|
|
323
|
+
}
|
|
324
|
+
const NUMERIC_KEYS = new Set(['max-age', 's-maxage', 'stale-if-error', 'stale-while-revalidate']);
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Parses a string Cache-Control header value into an object with the following structure:
|
|
328
|
+
*
|
|
329
|
+
* ```ts
|
|
330
|
+
* interface CacheControlValue {
|
|
331
|
+
* immutable?: boolean;
|
|
332
|
+
* 'max-age'?: number;
|
|
333
|
+
* 'must-revalidate'?: boolean;
|
|
334
|
+
* 'must-understand'?: boolean;
|
|
335
|
+
* 'no-cache'?: boolean;
|
|
336
|
+
* 'no-store'?: boolean;
|
|
337
|
+
* 'no-transform'?: boolean;
|
|
338
|
+
* 'only-if-cached'?: boolean;
|
|
339
|
+
* private?: boolean;
|
|
340
|
+
* 'proxy-revalidate'?: boolean;
|
|
341
|
+
* public?: boolean;
|
|
342
|
+
* 's-maxage'?: number;
|
|
343
|
+
* 'stale-if-error'?: number;
|
|
344
|
+
* 'stale-while-revalidate'?: number;
|
|
345
|
+
* }
|
|
346
|
+
* ```
|
|
347
|
+
* @method parseCacheControl
|
|
348
|
+
* @static
|
|
349
|
+
* @public
|
|
350
|
+
* @for @ember-data-mirror/request-utils
|
|
351
|
+
* @param {string} header
|
|
352
|
+
* @return {CacheControlValue}
|
|
353
|
+
*/
|
|
354
|
+
function parseCacheControl(header) {
|
|
355
|
+
let key = '';
|
|
356
|
+
let value = '';
|
|
357
|
+
let isParsingKey = true;
|
|
358
|
+
const cacheControlValue = {};
|
|
359
|
+
function parseCacheControlValue(stringToParse) {
|
|
360
|
+
const parsedValue = Number.parseInt(stringToParse);
|
|
361
|
+
assert(`Invalid Cache-Control value, expected a number but got - ${stringToParse}`, !Number.isNaN(parsedValue));
|
|
362
|
+
return parsedValue;
|
|
363
|
+
}
|
|
364
|
+
for (let i = 0; i < header.length; i++) {
|
|
365
|
+
const char = header.charAt(i);
|
|
366
|
+
if (char === ',') {
|
|
367
|
+
assert(`Invalid Cache-Control value, expected a value`, !isParsingKey || !NUMERIC_KEYS.has(key));
|
|
368
|
+
assert(`Invalid Cache-Control value, expected a value after "=" but got ","`, i === 0 || header.charAt(i - 1) !== '=');
|
|
369
|
+
isParsingKey = true;
|
|
370
|
+
// @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
|
|
371
|
+
cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
|
|
372
|
+
key = '';
|
|
373
|
+
value = '';
|
|
374
|
+
continue;
|
|
375
|
+
} else if (char === '=') {
|
|
376
|
+
assert(`Invalid Cache-Control value, expected a value after "="`, i + 1 !== header.length);
|
|
377
|
+
isParsingKey = false;
|
|
378
|
+
} else if (char === ' ' || char === `\t` || char === `\n`) {
|
|
379
|
+
continue;
|
|
380
|
+
} else if (isParsingKey) {
|
|
381
|
+
key += char;
|
|
382
|
+
} else {
|
|
383
|
+
value += char;
|
|
384
|
+
}
|
|
385
|
+
if (i === header.length - 1) {
|
|
386
|
+
// @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
|
|
387
|
+
cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return cacheControlValue;
|
|
391
|
+
}
|
|
392
|
+
function isStale(headers, expirationTime) {
|
|
393
|
+
// const age = headers.get('age');
|
|
394
|
+
// const cacheControl = parseCacheControl(headers.get('cache-control') || '');
|
|
395
|
+
// const expires = headers.get('expires');
|
|
396
|
+
// const lastModified = headers.get('last-modified');
|
|
397
|
+
const date = headers.get('date');
|
|
398
|
+
if (!date) {
|
|
399
|
+
return true;
|
|
400
|
+
}
|
|
401
|
+
const time = new Date(date).getTime();
|
|
402
|
+
const now = Date.now();
|
|
403
|
+
const deadline = time + expirationTime;
|
|
404
|
+
const result = now > deadline;
|
|
405
|
+
return result;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* A basic LifetimesService that can be added to the Store service.
|
|
409
|
+
*
|
|
410
|
+
* Determines staleness based on time since the request was last received from the API
|
|
411
|
+
* using the `date` header.
|
|
412
|
+
*
|
|
413
|
+
* Invalidates any request for which `cacheOptions.types` was provided when a createRecord
|
|
414
|
+
* request for that type is successful.
|
|
415
|
+
*
|
|
416
|
+
* This allows the Store's CacheHandler to determine if a request is expired and
|
|
417
|
+
* should be refetched upon next request.
|
|
418
|
+
*
|
|
419
|
+
* The `Fetch` handler provided by `@ember-data-mirror/request/fetch` will automatically
|
|
420
|
+
* add the `date` header to responses if it is not present.
|
|
421
|
+
*
|
|
422
|
+
* Note: Date headers do not have millisecond precision, so expiration times should
|
|
423
|
+
* generally be larger than 1000ms.
|
|
424
|
+
*
|
|
425
|
+
* Usage:
|
|
426
|
+
*
|
|
427
|
+
* ```ts
|
|
428
|
+
* import { LifetimesService } from '@ember-data-mirror/request-utils';
|
|
429
|
+
* import DataStore from '@ember-data-mirror/store';
|
|
430
|
+
*
|
|
431
|
+
* // ...
|
|
432
|
+
*
|
|
433
|
+
* export class Store extends DataStore {
|
|
434
|
+
* constructor(args) {
|
|
435
|
+
* super(args);
|
|
436
|
+
* this.lifetimes = new LifetimesService({ apiCacheSoftExpires: 30_000, apiCacheHardExpires: 60_000 });
|
|
437
|
+
* }
|
|
438
|
+
* }
|
|
439
|
+
* ```
|
|
440
|
+
*
|
|
441
|
+
* @class LifetimesService
|
|
442
|
+
* @public
|
|
443
|
+
* @module @ember-data-mirror/request-utils
|
|
444
|
+
*/
|
|
445
|
+
class LifetimesService {
|
|
446
|
+
_getStore(store) {
|
|
447
|
+
let set = this._stores.get(store);
|
|
448
|
+
if (!set) {
|
|
449
|
+
set = {
|
|
450
|
+
invalidated: new Set(),
|
|
451
|
+
types: new Map()
|
|
452
|
+
};
|
|
453
|
+
this._stores.set(store, set);
|
|
454
|
+
}
|
|
455
|
+
return set;
|
|
456
|
+
}
|
|
457
|
+
constructor(config) {
|
|
458
|
+
this._stores = new WeakMap();
|
|
459
|
+
const _config = arguments.length === 1 ? config : arguments[1];
|
|
460
|
+
deprecate(`Passing a Store to the LifetimesService is deprecated, please pass only a config instead.`, arguments.length === 1, {
|
|
461
|
+
id: 'ember-data-mirror:request-utils:lifetimes-service-store-arg',
|
|
462
|
+
since: {
|
|
463
|
+
enabled: '5.4',
|
|
464
|
+
available: '5.4'
|
|
465
|
+
},
|
|
466
|
+
for: '@ember-data-mirror/request-utils',
|
|
467
|
+
until: '6.0'
|
|
468
|
+
});
|
|
469
|
+
assert(`You must pass a config to the LifetimesService`, _config);
|
|
470
|
+
assert(`You must pass a apiCacheSoftExpires to the LifetimesService`, typeof _config.apiCacheSoftExpires === 'number');
|
|
471
|
+
assert(`You must pass a apiCacheHardExpires to the LifetimesService`, typeof _config.apiCacheHardExpires === 'number');
|
|
472
|
+
this.config = _config;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Invalidate a request by its identifier for a given store instance.
|
|
477
|
+
*
|
|
478
|
+
* While the store argument may seem redundant, the lifetimes service
|
|
479
|
+
* is designed to be shared across multiple stores / forks
|
|
480
|
+
* of the store.
|
|
481
|
+
*
|
|
482
|
+
* ```ts
|
|
483
|
+
* store.lifetimes.invalidateRequest(store, identifier);
|
|
484
|
+
* ```
|
|
485
|
+
*
|
|
486
|
+
* @method invalidateRequest
|
|
487
|
+
* @public
|
|
488
|
+
* @param {StableDocumentIdentifier} identifier
|
|
489
|
+
* @param {Store} store
|
|
490
|
+
*/
|
|
491
|
+
invalidateRequest(identifier, store) {
|
|
492
|
+
this._getStore(store).invalidated.add(identifier.lid);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Invalidate all requests associated to a specific type
|
|
497
|
+
* for a given store instance.
|
|
498
|
+
*
|
|
499
|
+
* While the store argument may seem redundant, the lifetimes service
|
|
500
|
+
* is designed to be shared across multiple stores / forks
|
|
501
|
+
* of the store.
|
|
502
|
+
*
|
|
503
|
+
* This invalidation is done automatically when using this service
|
|
504
|
+
* for both the CacheHandler and the LegacyNetworkHandler.
|
|
505
|
+
*
|
|
506
|
+
* ```ts
|
|
507
|
+
* store.lifetimes.invalidateRequestsForType(store, 'person');
|
|
508
|
+
* ```
|
|
509
|
+
*
|
|
510
|
+
* @method invalidateRequestsForType
|
|
511
|
+
* @public
|
|
512
|
+
* @param {string} type
|
|
513
|
+
* @param {Store} store
|
|
514
|
+
*/
|
|
515
|
+
invalidateRequestsForType(type, store) {
|
|
516
|
+
const storeCache = this._getStore(store);
|
|
517
|
+
const set = storeCache.types.get(type);
|
|
518
|
+
if (set) {
|
|
519
|
+
set.forEach(id => {
|
|
520
|
+
storeCache.invalidated.add(id);
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Invoked when a request has been fulfilled from the configured request handlers.
|
|
527
|
+
* This is invoked by the CacheHandler for both foreground and background requests
|
|
528
|
+
* once the cache has been updated.
|
|
529
|
+
*
|
|
530
|
+
* Note, this is invoked by the CacheHandler regardless of whether
|
|
531
|
+
* the request has a cache-key.
|
|
532
|
+
*
|
|
533
|
+
* This method should not be invoked directly by consumers.
|
|
534
|
+
*
|
|
535
|
+
* @method didRequest
|
|
536
|
+
* @public
|
|
537
|
+
* @param {ImmutableRequestInfo} request
|
|
538
|
+
* @param {ImmutableResponse} response
|
|
539
|
+
* @param {Store} store
|
|
540
|
+
* @param {StableDocumentIdentifier | null} identifier
|
|
541
|
+
* @return {void}
|
|
542
|
+
*/
|
|
543
|
+
didRequest(request, response, identifier, store) {
|
|
544
|
+
// if this is a successful createRecord request, invalidate the cacheKey for the type
|
|
545
|
+
if (request.op === 'createRecord') {
|
|
546
|
+
const statusNumber = response?.status ?? 0;
|
|
547
|
+
if (statusNumber >= 200 && statusNumber < 400) {
|
|
548
|
+
const types = new Set(request.records?.map(r => r.type));
|
|
549
|
+
types.forEach(type => {
|
|
550
|
+
this.invalidateRequestsForType(type, store);
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// add this document's cacheKey to a map for all associated types
|
|
555
|
+
// it is recommended to only use this for queries
|
|
556
|
+
} else if (identifier && request.cacheOptions?.types?.length) {
|
|
557
|
+
const storeCache = this._getStore(store);
|
|
558
|
+
request.cacheOptions?.types.forEach(type => {
|
|
559
|
+
const set = storeCache.types.get(type);
|
|
560
|
+
if (set) {
|
|
561
|
+
set.add(identifier.lid);
|
|
562
|
+
storeCache.invalidated.delete(identifier.lid);
|
|
563
|
+
} else {
|
|
564
|
+
storeCache.types.set(type, new Set([identifier.lid]));
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Invoked to determine if the request may be fulfilled from cache
|
|
572
|
+
* if possible.
|
|
573
|
+
*
|
|
574
|
+
* Note, this is only invoked by the CacheHandler if the request has
|
|
575
|
+
* a cache-key.
|
|
576
|
+
*
|
|
577
|
+
* If no cache entry is found or the entry is hard expired,
|
|
578
|
+
* the request will be fulfilled from the configured request handlers
|
|
579
|
+
* and the cache will be updated before returning the response.
|
|
580
|
+
*
|
|
581
|
+
* @method isHardExpired
|
|
582
|
+
* @public
|
|
583
|
+
* @param {StableDocumentIdentifier} identifier
|
|
584
|
+
* @param {Store} store
|
|
585
|
+
* @return {boolean} true if the request is considered hard expired
|
|
586
|
+
*/
|
|
587
|
+
isHardExpired(identifier, store) {
|
|
588
|
+
// if we are explicitly invalidated, we are hard expired
|
|
589
|
+
const storeCache = this._getStore(store);
|
|
590
|
+
if (storeCache.invalidated.has(identifier.lid)) {
|
|
591
|
+
return true;
|
|
592
|
+
}
|
|
593
|
+
const cache = store.cache;
|
|
594
|
+
const cached = cache.peekRequest(identifier);
|
|
595
|
+
return !cached || !cached.response || isStale(cached.response.headers, this.config.apiCacheHardExpires);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Invoked if `isHardExpired` is false to determine if the request
|
|
600
|
+
* should be update behind the scenes if cache data is already available.
|
|
601
|
+
*
|
|
602
|
+
* Note, this is only invoked by the CacheHandler if the request has
|
|
603
|
+
* a cache-key.
|
|
604
|
+
*
|
|
605
|
+
* If true, the request will be fulfilled from cache while a backgrounded
|
|
606
|
+
* request is made to update the cache via the configured request handlers.
|
|
607
|
+
*
|
|
608
|
+
* @method isSoftExpired
|
|
609
|
+
* @public
|
|
610
|
+
* @param {StableDocumentIdentifier} identifier
|
|
611
|
+
* @param {Store} store
|
|
612
|
+
* @return {boolean} true if the request is considered soft expired
|
|
613
|
+
*/
|
|
614
|
+
isSoftExpired(identifier, store) {
|
|
615
|
+
const cache = store.cache;
|
|
616
|
+
const cached = cache.peekRequest(identifier);
|
|
617
|
+
return !cached || !cached.response || isStale(cached.response.headers, this.config.apiCacheSoftExpires);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
export { LifetimesService, buildBaseURL, buildQueryParams, filterEmpty, parseCacheControl, setBuildURLConfig, sortQueryParams };
|