@soleil-se/app-util 5.2.2 → 5.4.0

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/CHANGELOG.md CHANGED
@@ -5,29 +5,29 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [5.2.2] - 2023-01-31
8
+ ## [5.4.0] - 2023-08-09
9
+
10
+ - Add `fetchJson` function to make requests to app routes or other resources.
11
+
12
+ ## [5.3.0] - 2023-07-06
9
13
 
10
- ### Changed
14
+ - Added helper functions for managing parameters in the URL-field.
15
+
16
+ ## [5.2.2] - 2023-01-31
11
17
 
12
18
  - Fix `parseParams` export.
13
19
 
14
20
  ## [5.2.1] - 2023-01-31
15
21
 
16
- ### Changed
17
-
18
22
  - Fix homepage url.
19
23
  - More lenient with peerDependency `@sitevision/api`.
20
24
 
21
25
  ## [5.2.0] - 2023-01-31
22
26
 
23
- ### Changed
24
-
25
27
  - New function `parseParams` to parse query parameters from an URL, URI or query string.
26
28
 
27
29
  ## [5.1.0] - 2022-05-27
28
30
 
29
- ### Changed
30
-
31
31
  - New function `stringifyParams` to stringify query parameters to a Sitevision compatible format.
32
32
  - Possible to pass a parameters object to `getRouteUri`.
33
33
  - All common constants and functions are now usable in hooks.
@@ -35,74 +35,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
35
35
 
36
36
  ## [5.0.0] - 2022-02-08
37
37
 
38
- ### Changed
39
-
40
38
  - Using WebApps 2 for rendering apps.
41
-
42
- ### Removed
43
-
44
- - `getAppData`, use `getAppProps` instead.
45
- - `server/render`, use `res.agnosticRender` for framework agnostic rendering.
46
- - `server/renderTemplate`, used for rendering underscore templates.
39
+ - Removed `getAppData`, use `getAppProps` instead.
40
+ - Removed `server/render`, use `res.agnosticRender` for framework agnostic rendering.
41
+ - Removed `server/renderTemplate`, used for rendering underscore templates.
47
42
 
48
43
  ## [4.2.1] - 2021-09-06
49
44
 
50
- ### Fixed
51
-
52
45
  - Underscore is misspelled in `renderTemplate`.
53
46
 
54
47
  ## [4.2.0] - 2021-08-20
55
48
 
56
- ### Added
57
-
58
- - `getAppProps` for getting props passed to the app when rendering.
59
-
60
- ### Changed
61
-
49
+ - Added `getAppProps` for getting props passed to the app when rendering.
62
50
  - `getAppData` deprecated due to confusion, use `getAppProps` instead.
63
51
 
64
52
  ## [4.1.4] - 2021-05-25
65
53
 
66
- ### Fixed
67
-
68
54
  - Return empty object instead of undefined when app data isn't set.
69
-
70
- ### Removed
71
-
72
55
  - Remove `vue` as optional dependency.
73
56
 
74
57
  ## [4.1.3] - 2021-03-31
75
58
 
76
- ### Fixed
77
-
78
59
  - Consistent rendering when using `serverServer` and `render` for Svelte.
79
-
80
- ### Added
81
-
82
60
  - Docs for Svelte `renderServer` function.
83
61
 
84
62
  ## [4.1.2] - 2021-02-24
85
63
 
86
- ### Fixed
87
-
88
64
  - Escape tags when parsing data to prevent closure of script tags.
89
65
 
90
66
  ## [4.1.1] - 2021-02-17
91
67
 
92
- ### Fixed
93
-
94
68
  - Validation error for `id` on script tags, even though it's allowed.
95
69
 
96
70
  ## [4.1.0] - 2021-02-17
97
71
 
98
- ### Changed
99
-
100
72
  - Put app data and metadata in script elements instead of data attributes.
101
73
 
102
74
  ## [4.0.1] - 2021-01-28
103
75
 
104
- ### Fixed
105
-
106
76
  - Crashes when no data is passed to app and then trying to call `getAppData`.
107
77
 
108
78
  ## [4.0.0] - 2021-01-27
@@ -110,17 +80,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
110
80
  A much needed major overhaul of the package.
111
81
  See [MIGRATION](./MIGRATION.md).
112
82
 
113
- ### Changed
114
-
115
83
  - Major refactoring of package.
116
84
  - Exports for render functions are moved.
117
85
  - All documented constants and functions from base import (`@soleil-api/webapp-util`) now works both in a server and client context.
118
86
  - Settings for selector is moved from server to client rendering functions.
119
-
120
- ### Removed
121
-
122
- - `noScript` option in `render` (formerly `renderApp`) has been removed. If a no script message is needed use the `html` option wrapped in `<noscript>`.
123
- - `@soleil-api/webapp-util/app-data` has been removed, use [getAppData](./README.md#getAppData) from `@soleil-api/webapp-util`.
87
+ - Removed `noScript` option in `render` (formerly `renderApp`) has been removed. If a no script message is needed use the `html` option wrapped in `<noscript>`.
88
+ - Removed `@soleil-api/webapp-util/app-data` has been removed, use [getAppData](./README.md#getAppData) from `@soleil-api/webapp-util`.
124
89
 
125
90
  ## [3.0.3] - 2020-11-03
126
91
 
@@ -132,86 +97,56 @@ See [MIGRATION](./MIGRATION.md).
132
97
 
133
98
  ## [3.0.1] - 2020-09-28
134
99
 
135
- ### Added
136
-
137
100
  - Homepage link
138
101
 
139
102
  ## [3.0.0] - 2020-09-28
140
103
 
141
- ### Added
142
-
143
104
  - Svelte support.
144
105
  - New exports:
145
106
  - `uniqueId` - A unique id for the app instance.
146
107
 
147
108
  ## [2.4.1] - 2020-09-01
148
109
 
149
- ### Fixed
150
-
151
110
  - App data with single quotes crashes app in edit mode, use double quotes instead.
152
111
 
153
112
  ## [2.4.0] - 2020-05-26
154
113
 
155
- ### Fixed
156
-
157
114
  - `getViewUri` returns correct URI when in offline mode and in the Addons view.
158
115
 
159
116
  ## [2.3.0] - 2020-05-22
160
117
 
161
- ### Added
162
-
163
118
  - `renderApp` now accepts `req` as a setting to opimize script loading when multiple instances of the app exists. If `req` is present the script will only be loaded once in all browsers except IE11 that needs a unique script src for the currentScript polyfill to work.
164
-
165
- ### Fixed
166
-
167
119
  - `noScript` in `renderApp` was not wrapped in a `<noscript>` tag.
168
120
 
169
121
  ## [2.2.0] - 2020-05-20
170
122
 
171
- ### Added
172
-
173
123
  - `renderTemplate` function is now available inside templates rendered by the function.
174
124
 
175
125
  ## [2.1.4] - 2020-04-07
176
126
 
177
- ### Fixed
178
-
179
127
  - `getViewUri` had incorrect portlet ID.
180
128
 
181
129
  ## [2.1.3] - 2020-02-25
182
130
 
183
- ### Fixed
184
-
185
131
  - Add timestamp to script url in edit mode as well.
186
132
 
187
133
  ## [2.1.2] - 2020-02-21
188
134
 
189
- ### Fixed
190
-
191
135
  - Wrapped `renderApp` script in svDocReady in edit mode to be sure it executes when other bundles are loaded.
192
136
 
193
137
  ## [2.1.1] - 2020-02-14
194
138
 
195
- ### Changed
196
-
197
139
  - Updated readme, heading levels and examples.
198
140
 
199
141
  ## [2.1.0] - 2020-02-14
200
142
 
201
- ### Added
202
-
203
143
  - App data import in client, `@soleil-api/webapp-util/app-data`.
204
144
  - `getViewUri` to get the URI that also renders the page.
205
145
  - `isOnline` to see if the app is online.
206
-
207
- ### Changed
208
-
209
146
  - `vue` is now an optional depedency.
210
147
 
211
148
  ## [2.0.0] - 2020-02-12
212
149
 
213
- ### Changed
214
-
215
150
  - Now using `currentScript` to reference the script element the app is running in to pass data when using `renderApp`.
216
151
  - `renderApp` is no longer using appName.
217
152
  - `render` is now called directly in `./app_src/client/index.js`.
package/README.md CHANGED
@@ -52,7 +52,7 @@ Integrity check failed for "@soleil-se/webapp-util" (computed integrity doesn...
52
52
  Migrating from version 4?
53
53
  See [MIGRATION](./MIGRATION.md).
54
54
 
55
- ## API
55
+ ## Common
56
56
 
57
57
  All imports from base package are available both on the server and client.
58
58
 
@@ -180,7 +180,7 @@ Stringify an object to a query string compatible with Sitevision.
180
180
  | Param | Type | Default | Description |
181
181
  | --- | --- | --- | --- |
182
182
  | params | `Object` | | Object with parameters to stringify. |
183
- | [options] | `Object` | `{}` | Settings object. |
183
+ | [options] | `Object` | `{}` | Options object. |
184
184
  | [options.addQueryPrefix] | `Boolean` | `false` | If a leading `?` should be added to the string. |
185
185
 
186
186
  ```js
@@ -210,6 +210,151 @@ const params = parseParams('?foo=bar&arr[]=1&arr[]=2');
210
210
  // { foo: 'bar', arr: [1, 2] }
211
211
  ```
212
212
 
213
+ ## Client
214
+
215
+ Following API:s are available in a client context.
216
+
217
+ ### Fetch
218
+
219
+ Fetch wrapper for calling app routes, rest-api or external resources.
220
+
221
+ #### fetchJson() => `Promise<Object>`
222
+
223
+ | Param | Type | Default | Description |
224
+ | --- | --- | --- | --- |
225
+ | uri | `String` | | URI for resource |
226
+ | [options] | `Object` | `{}` | Options object, two custom options rest is standard [fetch options](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) |
227
+ | [options.params] | `Object` | `{}` | Object with parameters to be appended to the URI |
228
+ | [options.retries] | `Number` | `0` | Number of retries if the request times out. |
229
+
230
+ **Returns**: `Promise<Object>` - Promise containing parsed JSON-data.
231
+ **Throws** `Error` - Extended error object with custom properties for `status`, `aborted` and other JSON-data returned by the request.
232
+
233
+ Most common usage is getting data from a route in the current app.
234
+
235
+ ```js
236
+ import { fetchJson } from '@soleil-se/webapp-util/client';
237
+
238
+ async function getItems() {
239
+ const params = { query: 'foo', start: 0, num: 10 };
240
+ const result = await fetchJson('/items', { params });
241
+ console.log(result);
242
+ }
243
+ ```
244
+
245
+ Posting form data.
246
+
247
+ ```js
248
+ import { fetchJson } from '@soleil-se/webapp-util/client';
249
+
250
+ async function postForm() {
251
+ const body = new FormData();
252
+ body.append('name', 'Foo');
253
+ body.append('mail', 'foo@bar.com');
254
+
255
+ const result = await fetchJson('/create', { method: 'POST', body }));
256
+ console.log(result);
257
+ }
258
+ ```
259
+
260
+ Specify number of retries if a request times out.
261
+
262
+ ```js
263
+ import { fetchJson } from '@soleil-se/webapp-util/client';
264
+
265
+ async function getItems() {
266
+ const params = { query: 'foo', start: 0, num: 10 };
267
+ const result = await fetchJson('/items', { params, retries: 5 });
268
+ console.log(result);
269
+ }
270
+ ```
271
+
272
+ Handle aborted requests called in rapid succession, for example searching when typing.
273
+
274
+ ```js
275
+ import { fetchJson } from '@soleil-se/webapp-util/client';
276
+
277
+ async function onInput() {
278
+ const params = { query: 'foo' };
279
+ try {
280
+ const result = await fetchJson('/search', { params });
281
+ console.log(result);
282
+ } catch(e) {
283
+ // Ignore aborts due to new search.
284
+ if(e.aborted) return;
285
+ // Handle error as usual.
286
+ }
287
+ }
288
+ ```
289
+
290
+ ### URL Parameters
291
+
292
+ Helper functions setting, getting, updating and clearing query parameters in the URL-field.
293
+
294
+ #### getUrlParams() ⇒ `Object`
295
+
296
+ Get parameters from the URL-field.
297
+
298
+ **Returns**: `Object` - Parameters in URL-field.
299
+
300
+ ```js
301
+ import { getUrlParams } from '@soleil-se/webapp-util/client';
302
+
303
+ const params = getUrlParams();
304
+ ```
305
+
306
+ #### getUrlParam() ⇒ `String|Array[String]`
307
+
308
+ Get single parameter from the URL-field.
309
+
310
+ **Returns**: `String|Array[String]` - Parameter value.
311
+
312
+ ```js
313
+ import { getUrlParam } from '@soleil-se/webapp-util/client';
314
+
315
+ const param = getUrlParam('name');
316
+ ```
317
+
318
+ #### setUrlParams(params)
319
+
320
+ Set parameters in the URL-field, overwriting other parameters.
321
+
322
+ | Param | Type | Default | Description |
323
+ | --- | --- | --- | --- |
324
+ | params | `Object` | | Object with parameters to set in the URL-field. |
325
+
326
+ ```js
327
+ import { setUrlParams } from '@soleil-se/webapp-util/client';
328
+
329
+ setUrlParams({ foo: 'bar', arr: [1, 2] });
330
+ ```
331
+
332
+ #### updateUrlParams(params)
333
+
334
+ Update parameters in the URL-field, merging with existing parameters
335
+
336
+ **Returns**: `String` - Stringified parameters.
337
+
338
+ | Param | Type | Default | Description |
339
+ | --- | --- | --- | --- |
340
+ | params | `Object` | | Object with parameters to add to the URL-field. |
341
+
342
+ ```js
343
+ import { updateUrlParams } from '@soleil-se/webapp-util/client';
344
+
345
+ updateUrlParams({ foo: 'bar', arr: [1, 2] });
346
+ ```
347
+
348
+ #### clearUrlParams()
349
+
350
+ Clear parameters in the URL-field
351
+
352
+ ```js
353
+ import { clearUrlParams } from '@soleil-se/webapp-util/client';
354
+
355
+ clearUrlParams();
356
+ ```
357
+
213
358
  ## Rendering
214
359
 
215
360
  * [Svelte](./docs/1.svelte.md)
@@ -0,0 +1,48 @@
1
+ import { getRouteUri, stringifyParams } from '../../common';
2
+
3
+ function getUrl(uri, params) {
4
+ if (uri.startsWith('/rest-api') || uri.startsWith('/appresource') || !uri.startsWith('/')) {
5
+ return uri + stringifyParams(params, { addQueryPrefix: true });
6
+ }
7
+ return getRouteUri(uri, params);
8
+ }
9
+
10
+ function toJson(response) {
11
+ try {
12
+ return response.json();
13
+ } catch (e) {
14
+ return {};
15
+ }
16
+ }
17
+
18
+ async function handleResponse(response) {
19
+ const json = await toJson(response);
20
+ if (!response.ok) {
21
+ const error = new Error(json?.message || response?.statusText);
22
+ Object.entries(json).forEach(([key, value]) => {
23
+ error[key] = value;
24
+ });
25
+ error.status = response.status;
26
+ throw error;
27
+ }
28
+
29
+ return json;
30
+ }
31
+
32
+ const controllers = {};
33
+
34
+ export default function fetchJson(uri, { params = {}, retries = 0, ...options } = {}) {
35
+ if (controllers[uri]) controllers[uri].abort();
36
+ controllers[uri] = new AbortController();
37
+ return fetch(getUrl(uri, params), { signal: controllers[uri].signal, ...options })
38
+ .then(handleResponse)
39
+ .catch((error) => {
40
+ const isTimeout = error.status === 504 || error.status === 408 || error.message.includes('SocketTimeoutException');
41
+ if (isTimeout && retries > 0) {
42
+ return fetchJson(uri, { ...options, params, retries: retries - 1 });
43
+ }
44
+ // eslint-disable-next-line no-param-reassign
45
+ error.aborted = error.name === 'AbortError';
46
+ return Promise.reject(error);
47
+ });
48
+ }
@@ -0,0 +1,9 @@
1
+ export {
2
+ getUrlParam,
3
+ getUrlParams,
4
+ setUrlParams,
5
+ updateUrlParams,
6
+ clearUrlParams,
7
+ } from './url-params';
8
+
9
+ export { default as fetchJson } from './fetch-json';
@@ -0,0 +1,52 @@
1
+ import { stringifyParams, parseParams } from '../../common';
2
+
3
+ const isEmpty = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
4
+
5
+ /**
6
+ * Set query parameters in the url-field.
7
+ * @param {Object} obj - Values to be set.
8
+ * @param {Object} [options] Optional options.
9
+ * @param {Boolean} [options.scoped = false] If parameter keys should be scoped to current app.
10
+ */
11
+ export function setUrlParams(params) {
12
+ window.history.replaceState({}, '', (isEmpty(params) ? window.location.pathname : `?${stringifyParams(params)}`));
13
+ }
14
+
15
+ /**
16
+ * Get query parameter from the url-field.
17
+ */
18
+ export function getUrlParam(key) {
19
+ const params = parseParams(window.location.search.substring(1));
20
+ return params[key];
21
+ }
22
+
23
+ /**
24
+ * Get query parameters from the url-field.
25
+ */
26
+ export function getUrlParams() {
27
+ const params = parseParams(window.location.search.substring(1));
28
+ return params;
29
+ }
30
+
31
+ /**
32
+ * Clear query parameters in the url-field.
33
+ */
34
+ export function clearUrlParams() {
35
+ window.history.replaceState({}, '', window.location.pathname);
36
+ }
37
+
38
+ /**
39
+ * Updates query parameters in the url-field.
40
+ * @param {Object} params - Values to be updated.
41
+ */
42
+ export function updateUrlParams(params) {
43
+ setUrlParams(Object.assign(getUrlParams(), params));
44
+ }
45
+
46
+ export default {
47
+ getUrlParam,
48
+ setUrlParams,
49
+ getUrlParams,
50
+ clearUrlParams,
51
+ updateUrlParams,
52
+ };
package/common/index.js CHANGED
@@ -1,4 +1,3 @@
1
- /* global document console */
2
1
  /* eslint-disable global-require */
3
2
  import router from '@sitevision/api/common/router';
4
3
  import app from '@sitevision/api/common/app';
@@ -116,7 +115,7 @@ export function parseParams(url = '') {
116
115
  * @param {object} params Query parameters.
117
116
  * @returns {string} URI for route.
118
117
  */
119
- export function getRouteUri(route = '', params) {
118
+ export function getRouteUri(route = '', params = undefined) {
120
119
  const path = route.replace(leadingSlashes, '');
121
120
  const qs = stringifyParams(params, { addQueryPrefix: true });
122
121
  if (router?.getStandaloneUrl) {
@@ -133,13 +132,13 @@ export function getRouteUri(route = '', params) {
133
132
  * @param {string} route A route.
134
133
  * @returns {string} URI for view.
135
134
  */
136
- export function getViewUri(route = '', query) {
135
+ export function getViewUri(route = '', params = undefined) {
137
136
  if (!router?.getUrl) {
138
137
  console.warn('[@soleil-api/webapp-util] getViewUri requires router.getUrl support.');
139
138
  return undefined;
140
139
  }
141
140
 
142
- return router.getUrl(route, query);
141
+ return router.getUrl(route, params);
143
142
  }
144
143
 
145
144
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soleil-se/app-util",
3
- "version": "5.2.2",
3
+ "version": "5.4.0",
4
4
  "description": "Utility and rendering functions for WebApps.",
5
5
  "main": "./common/index.js",
6
6
  "author": "Soleil AB",
@@ -14,6 +14,6 @@
14
14
  "peerDependencies": {
15
15
  "@sitevision/api": "*"
16
16
  },
17
- "gitHead": "53b207511538040495c560637273434daff093fa",
17
+ "gitHead": "b590af917fa521db8bdb7e6f97bd35dffa50a0de",
18
18
  "dependencies": {}
19
19
  }
@@ -1,4 +0,0 @@
1
- module.exports = {
2
- extends: '@soleil/eslint-config-sitevision/client',
3
- root: true,
4
- };
package/docs/2.vue.md DELETED
@@ -1,57 +0,0 @@
1
- # Vue (DEPRECATED)
2
-
3
- Sitevision only supports client side rendering with Vue.
4
-
5
- ## index.js
6
-
7
- Render an app with only client code.
8
- `index.js`
9
-
10
- ```javascript
11
- import router from '@sitevision/api/common/router';
12
-
13
- router.get('/', (req, res) => {
14
- const props = { foo: 'bar' };
15
- res.agnosticRender('', props)
16
- });
17
- ```
18
-
19
- ## main.js
20
-
21
- ### `render(App, { target, props })`
22
-
23
- `@soleil-api/webapp-util/client/vue`
24
-
25
- Renders a client side Vue application.
26
-
27
- **Returns**: <code>\*</code> - Initialized Vue app.
28
-
29
- | Param | Type | Default | Description |
30
- | --- | --- | --- | --- |
31
- | App | <code>\*</code> | | Svelte app root component. |
32
- | [settings] | <code>Object</code> | <code>{}</code> | Settings object. |
33
- | [settings.target] | <code>Element</code> | | Target where app should be mounted. |
34
- | [settings.props] | <code>Object</code> | | Root component props. |
35
-
36
- `main.js`
37
-
38
- ```javascript
39
- import { render } from '@soleil-api/webapp-util/client/vue';
40
- import App from './App.vue';
41
-
42
- export default (props, target) => {
43
- render(App, { props, target });
44
- };
45
- ```
46
-
47
- Mount the app in another element:
48
- `main.js`
49
-
50
- ```javascript
51
- import { render } from '@soleil-api/webapp-util/client/vue';
52
- import App from './App.vue';
53
-
54
- export default (props) => {
55
- render(App, { props, target: document.querySelector('#mount_app_here') });
56
- };
57
- ```