@inglorious/store 12.3.0 → 12.5.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/README.md +84 -0
- package/package.json +12 -8
- package/src/behaviors/async.js +130 -66
- package/src/behaviors/storage.js +105 -0
- package/types/behaviors/async.d.ts +63 -0
- package/types/behaviors/storage.d.ts +22 -0
package/README.md
CHANGED
|
@@ -558,8 +558,60 @@ Two things to keep in mind:
|
|
|
558
558
|
- **`entity` ends at the first `await`.** `entity`, and every object or array read from it, is a draft of the current update, revoked when the update ends, and the update does not wait for your `await`. After it, writing to `entity` or reading anything taken from it throws. Write before the first `await`, then notify an event that does the rest, as `todosLoaded` does above. The same goes for payloads: pass a copy (`{ ...entity.values }`), not the draft, to a handler that reads it after an `await`.
|
|
559
559
|
- **`api.getEntity()` reads the state from before the update.** A handler cannot see what an earlier handler in the same chain of events changed: see [State swapping](#state-swapping).
|
|
560
560
|
|
|
561
|
+
### `handleRequest`
|
|
562
|
+
|
|
563
|
+
Most async work is a request whose progress the entity shows: loading, then the result or what went wrong. `handleRequest` does that bookkeeping, and it's the one to reach for first:
|
|
564
|
+
|
|
565
|
+
```ts
|
|
566
|
+
import { handleRequest } from "@inglorious/store/async"
|
|
567
|
+
|
|
568
|
+
const JobList = {
|
|
569
|
+
...handleRequest("search", {
|
|
570
|
+
run: (query) => api.searchJobs(query),
|
|
571
|
+
success(entity, jobs) {
|
|
572
|
+
entity.jobs = jobs
|
|
573
|
+
},
|
|
574
|
+
}),
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
api.notify("#jobList:search", "photographer")
|
|
578
|
+
```
|
|
579
|
+
|
|
580
|
+
- **Status**: `entity.status` is `"loading"` from the start, then `"success"` or `"error"`. Set its first value, such as `"idle"`, in `create`.
|
|
581
|
+
- **Error**: `entity.error` is cleared when a call starts and set when it fails, to the error's message by default. `toError` turns it into what the screen needs, such as a translation key. The `error` handler receives that value after it is set, and can change what the entity shows, such as moving to another step for an error it expects.
|
|
582
|
+
- **Only the latest call counts**: the answer of a call that a newer one replaced is dropped, success and failure alike, so a slow search never overwrites a quicker, later one. `isLatestOnly: false` lets every call count, as when saving several items at once.
|
|
583
|
+
- **Several requests on one entity**: give each its own fields.
|
|
584
|
+
- **Scope**: `scope` sends the lifecycle events to the entity (the default), its type or everyone, as in `handleAsync` (see [Event scoping](#event-scoping)).
|
|
585
|
+
|
|
586
|
+
```ts
|
|
587
|
+
const Profile = {
|
|
588
|
+
...handleRequest(
|
|
589
|
+
"save",
|
|
590
|
+
{
|
|
591
|
+
run: (profile) => api.saveProfile(profile),
|
|
592
|
+
},
|
|
593
|
+
{ status: "saveStatus", error: "saveError", toError: errorKey },
|
|
594
|
+
),
|
|
595
|
+
...handleRequest(
|
|
596
|
+
"avatarUpload",
|
|
597
|
+
{ run: uploadAvatar },
|
|
598
|
+
{ status: "avatarStatus", error: "avatarError" },
|
|
599
|
+
),
|
|
600
|
+
}
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
To wait until someone stops typing, debounce the event that starts the request with `withDebounce` from `@inglorious/web`. Debouncing starts fewer calls; dropping outdated answers covers the ones that still overlap:
|
|
604
|
+
|
|
605
|
+
```ts
|
|
606
|
+
const types = { JobList: [JobList, withDebounce(300, ["search"])] }
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
The handlers and events are those of `handleAsync`, below, so `optimistic` wraps a request too.
|
|
610
|
+
|
|
561
611
|
### `handleAsync`
|
|
562
612
|
|
|
613
|
+
`handleAsync` is the lower level `handleRequest` is built on: it keeps no status and no error, and lets every call's answer through. Use it for async work the entity doesn't show, such as saving a preference in the background, a call whose failure is only logged, or a check that must keep its last answer when it fails.
|
|
614
|
+
|
|
563
615
|
The `handleAsync` helper generates a set of event handlers representing the lifecycle of an async operation.
|
|
564
616
|
|
|
565
617
|
```ts
|
|
@@ -753,6 +805,38 @@ Available scopes:
|
|
|
753
805
|
|
|
754
806
|
---
|
|
755
807
|
|
|
808
|
+
### `withStorage`
|
|
809
|
+
|
|
810
|
+
The entity is the one source of truth; keeping some of it between visits is a byproduct. `withStorage` brings the fields back when the entity is created, before the type's own `create`, and writes them back after any handler that changes them:
|
|
811
|
+
|
|
812
|
+
```ts
|
|
813
|
+
import { withStorage } from "@inglorious/store/storage"
|
|
814
|
+
|
|
815
|
+
const Settings = {
|
|
816
|
+
create(entity) {
|
|
817
|
+
entity.theme ??= "light" // kept from last time, else light
|
|
818
|
+
},
|
|
819
|
+
themeSet(entity, theme) {
|
|
820
|
+
entity.theme = theme // saved along the way
|
|
821
|
+
},
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const types = {
|
|
825
|
+
Settings: [Settings, withStorage(["theme"])],
|
|
826
|
+
Draft: [
|
|
827
|
+
Draft,
|
|
828
|
+
withStorage(["text"], { key: "draft", storage: () => sessionStorage }),
|
|
829
|
+
],
|
|
830
|
+
}
|
|
831
|
+
```
|
|
832
|
+
|
|
833
|
+
- Nothing reads storage but `withStorage`: the app reads the entity, and the rest follows.
|
|
834
|
+
- Put it last in the type's array: it saves after the handlers before it.
|
|
835
|
+
- `key` names where the fields go (the entity's id by default), or derives it from the entity. `storage` is any Web Storage, `localStorage` by default.
|
|
836
|
+
- Storage that is missing, full or refusing, as in a private window, only means nothing is kept.
|
|
837
|
+
|
|
838
|
+
---
|
|
839
|
+
|
|
756
840
|
## 🧩 Migrating from Redux Toolkit (RTK)
|
|
757
841
|
|
|
758
842
|
Inglorious Store now provides utilities to **gradually migrate from RTK slices and thunks**, leveraging `handleAsync` to simplify async logic.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/store",
|
|
3
|
-
"version": "12.
|
|
3
|
+
"version": "12.5.0",
|
|
4
4
|
"description": "A state manager for real-time, collaborative apps, inspired by game development patterns and compatible with Redux.",
|
|
5
5
|
"author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
|
|
6
6
|
"license": "MIT",
|
|
@@ -48,6 +48,10 @@
|
|
|
48
48
|
"types": "./types/behaviors/optimistic.d.ts",
|
|
49
49
|
"import": "./src/behaviors/optimistic.js"
|
|
50
50
|
},
|
|
51
|
+
"./storage": {
|
|
52
|
+
"types": "./types/behaviors/storage.d.ts",
|
|
53
|
+
"import": "./src/behaviors/storage.js"
|
|
54
|
+
},
|
|
51
55
|
"./fsm": {
|
|
52
56
|
"types": "./types/behaviors/state-machine/fsm.d.ts",
|
|
53
57
|
"import": "./src/behaviors/state-machine/fsm.js"
|
|
@@ -75,19 +79,19 @@
|
|
|
75
79
|
},
|
|
76
80
|
"sideEffects": false,
|
|
77
81
|
"dependencies": {
|
|
78
|
-
"mutative": "^
|
|
82
|
+
"mutative": "^2.0.2"
|
|
79
83
|
},
|
|
80
84
|
"peerDependencies": {
|
|
81
|
-
"@inglorious/utils": "^5.
|
|
85
|
+
"@inglorious/utils": "^5.3.0"
|
|
82
86
|
},
|
|
83
87
|
"devDependencies": {
|
|
84
88
|
"@inglorious/eslint-config": "1.2.0",
|
|
85
|
-
"@inglorious/utils": "5.
|
|
86
|
-
"@reduxjs/toolkit": "^2.
|
|
87
|
-
"prettier": "^3.9.
|
|
89
|
+
"@inglorious/utils": "5.3.0",
|
|
90
|
+
"@reduxjs/toolkit": "^2.14.0",
|
|
91
|
+
"prettier": "^3.9.10",
|
|
88
92
|
"typescript": "~7.0.2",
|
|
89
|
-
"vite": "^8.
|
|
90
|
-
"vitest": "^5.
|
|
93
|
+
"vite": "^8.3.8",
|
|
94
|
+
"vitest": "^5.1.0"
|
|
91
95
|
},
|
|
92
96
|
"engines": {
|
|
93
97
|
"node": ">= 26"
|
package/src/behaviors/async.js
CHANGED
|
@@ -1,9 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handlers of a request: a call whose progress the entity shows. The
|
|
3
|
+
* entity's `status` is `"loading"` from the start, then `"success"` or
|
|
4
|
+
* `"error"`, and its `error` holds what went wrong. Only the latest call
|
|
5
|
+
* counts: the answer of a call that a newer one replaced is dropped, so a slow
|
|
6
|
+
* search never overwrites a quicker, later one. Prefer it to `handleAsync`
|
|
7
|
+
* whenever the entity shows that something is happening.
|
|
8
|
+
*
|
|
9
|
+
* @template {import('../store').BaseEntity} TEntity
|
|
10
|
+
* @template TPayload
|
|
11
|
+
* @template TResult
|
|
12
|
+
*
|
|
13
|
+
* @param {string} type The event that starts the request, which `withDebounce`
|
|
14
|
+
* can wrap. Its lifecycle events are those of `handleAsync`.
|
|
15
|
+
* @param {Object} handlers As `handleAsync`'s. `error` receives the error as
|
|
16
|
+
* `toError` turns it, after `error` is set: it can change what the entity
|
|
17
|
+
* shows, such as moving to another step for an error it expects.
|
|
18
|
+
* @param {Object} [options]
|
|
19
|
+
* @param {string} [options.status="status"] The field for the status, when
|
|
20
|
+
* the entity has several requests, such as `"saveStatus"`.
|
|
21
|
+
* @param {string} [options.error="error"] The field for the error.
|
|
22
|
+
* @param {(error: unknown) => unknown} [options.toError] What to store as the
|
|
23
|
+
* error, such as a translation key. Defaults to the error's message.
|
|
24
|
+
* @param {boolean} [options.isLatestOnly=true] Whether a call replaced by a
|
|
25
|
+
* newer one is ignored. Turn it off for calls that all count, such as saving
|
|
26
|
+
* several items at once.
|
|
27
|
+
* @param {"entity" | "type" | "global"} [options.scope="entity"] Where the
|
|
28
|
+
* lifecycle events go, as in `handleAsync`.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* const JobList = {
|
|
32
|
+
* ...handleRequest("search", {
|
|
33
|
+
* run: (query) => api.searchJobs(query),
|
|
34
|
+
* success(entity, jobs) {
|
|
35
|
+
* entity.jobs = jobs
|
|
36
|
+
* },
|
|
37
|
+
* }),
|
|
38
|
+
* }
|
|
39
|
+
*
|
|
40
|
+
* const types = { JobList: [JobList, withDebounce(300, ["search"])] }
|
|
41
|
+
*/
|
|
42
|
+
export function handleRequest(type, handlers, options = {}) {
|
|
43
|
+
const {
|
|
44
|
+
status = "status",
|
|
45
|
+
error: errorField = "error",
|
|
46
|
+
toError = messageOf,
|
|
47
|
+
isLatestOnly = true,
|
|
48
|
+
scope = "entity",
|
|
49
|
+
} = options
|
|
50
|
+
|
|
51
|
+
const base = handleAsync(
|
|
52
|
+
type,
|
|
53
|
+
{
|
|
54
|
+
start(entity, payload, api) {
|
|
55
|
+
entity[status] = "loading"
|
|
56
|
+
entity[errorField] = null
|
|
57
|
+
handlers.start?.(entity, payload, api)
|
|
58
|
+
},
|
|
59
|
+
run: handlers.run,
|
|
60
|
+
success(entity, result, api) {
|
|
61
|
+
entity[status] = "success"
|
|
62
|
+
handlers.success?.(entity, result, api)
|
|
63
|
+
},
|
|
64
|
+
error(entity, error, api) {
|
|
65
|
+
const value = toError(error)
|
|
66
|
+
entity[status] = "error"
|
|
67
|
+
entity[errorField] = value
|
|
68
|
+
handlers.error?.(entity, value, api)
|
|
69
|
+
},
|
|
70
|
+
finally: handlers.finally,
|
|
71
|
+
},
|
|
72
|
+
{ scope },
|
|
73
|
+
)
|
|
74
|
+
if (!isLatestOnly) return base
|
|
75
|
+
|
|
76
|
+
/** The latest call of each entity. */
|
|
77
|
+
const latest = new Map()
|
|
78
|
+
const startEvent = `${type}Start`
|
|
79
|
+
const isCurrent = (entity, { callId }) => latest.get(entity.id) === callId
|
|
80
|
+
const unlessStale = (event) => (entity, payload, api) => {
|
|
81
|
+
if (isCurrent(entity, payload)) base[event](entity, payload, api)
|
|
82
|
+
}
|
|
83
|
+
const finallyEvent = `${type}Finally`
|
|
84
|
+
|
|
85
|
+
const request = {
|
|
86
|
+
...base,
|
|
87
|
+
|
|
88
|
+
[startEvent](entity, event, api) {
|
|
89
|
+
latest.set(entity.id, event.callId)
|
|
90
|
+
base[startEvent](entity, event, api)
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
[`${type}Success`]: unlessStale(`${type}Success`),
|
|
94
|
+
[`${type}Error`]: unlessStale(`${type}Error`),
|
|
95
|
+
|
|
96
|
+
[finallyEvent](entity, event, api) {
|
|
97
|
+
if (!isCurrent(entity, event)) return
|
|
98
|
+
latest.delete(entity.id)
|
|
99
|
+
base[finallyEvent](entity, event, api)
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
Object.defineProperty(request, ASYNC_META, {
|
|
104
|
+
value: { type, scope },
|
|
105
|
+
enumerable: false,
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
return request
|
|
109
|
+
}
|
|
110
|
+
|
|
1
111
|
/**
|
|
2
112
|
* Creates a set of event handlers for managing an asynchronous operation lifecycle.
|
|
3
113
|
*
|
|
4
114
|
* This helper generates handlers for all stages of an async operation: start, run,
|
|
5
115
|
* success, error, and finally. The lifecycle events are automatically scoped based
|
|
6
|
-
* on the provided options.
|
|
116
|
+
* on the provided options. For a call whose progress the entity shows, use
|
|
117
|
+
* `handleRequest`, which keeps the status and error and drops outdated answers;
|
|
118
|
+
* `handleAsync` is for the rest, such as saving in the background or calls whose
|
|
119
|
+
* failure only gets logged.
|
|
7
120
|
*
|
|
8
121
|
* @template {import('../store').BaseEntity} TEntity - The entity type
|
|
9
122
|
* @template TPayload - The payload type passed to the operation
|
|
@@ -14,8 +127,7 @@
|
|
|
14
127
|
*
|
|
15
128
|
* @param {Object} handlers - The handler functions for each lifecycle stage.
|
|
16
129
|
* @param {(entity: TEntity, payload: TPayload, api: import('../store').Api) => void} [handlers.start]
|
|
17
|
-
* Called synchronously before the async operation starts.
|
|
18
|
-
* Use for setting loading states. Receives: (entity, payload, api)
|
|
130
|
+
* Called synchronously before the async operation starts. Receives: (entity, payload, api)
|
|
19
131
|
* @param {(payload: TPayload, api: import('../store').Api) => Promise<TResult> | TResult} handlers.run
|
|
20
132
|
* The async operation to perform. Must return a Promise or value.
|
|
21
133
|
* **Note:** Receives (payload, api) - NOT entity. Entity state should be modified in other handlers.
|
|
@@ -26,15 +138,14 @@
|
|
|
26
138
|
* Called when the operation fails.
|
|
27
139
|
* Receives: (entity, error, api) where error is the caught exception
|
|
28
140
|
* @param {(entity: TEntity, api: import('../store').Api) => void} [handlers.finally]
|
|
29
|
-
* Called after the operation completes (success or failure).
|
|
30
|
-
* Use for cleanup, resetting loading states. Receives: (entity, api)
|
|
141
|
+
* Called after the operation completes (success or failure). Receives: (entity, api)
|
|
31
142
|
*
|
|
32
143
|
* @param {Object} [options] - Configuration options.
|
|
33
144
|
* @param {"entity" | "type" | "global"} [options.scope="entity"]
|
|
34
145
|
* Controls how lifecycle events are routed:
|
|
35
146
|
* - "entity": notify `#entityId:event` (default, safest - events only affect the triggering entity)
|
|
36
147
|
* - "type": notify `typeName:event` (broadcasts to all entities of this type)
|
|
37
|
-
* - "global": notify `event` (global broadcast to any listener)
|
|
148
|
+
* - "global": notify `event` (global broadcast to any listener, as games often want)
|
|
38
149
|
*
|
|
39
150
|
* Each call gets a `callId`, and every event of that call carries it: `Start`
|
|
40
151
|
* and `Run` get `{ payload, callId }`, `Success` gets `{ result, callId }`,
|
|
@@ -50,37 +161,20 @@
|
|
|
50
161
|
* - `[typeFinally]`: Executes the finally handler
|
|
51
162
|
*
|
|
52
163
|
* @example
|
|
53
|
-
* //
|
|
54
|
-
* const
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* },
|
|
59
|
-
*
|
|
60
|
-
* ...handleAsync('fetchTodos', {
|
|
61
|
-
* start(entity) {
|
|
62
|
-
* entity.status = 'loading'
|
|
164
|
+
* // Saves in the background: a failure is only logged
|
|
165
|
+
* const preferences = {
|
|
166
|
+
* ...handleAsync('localeSave', {
|
|
167
|
+
* run(locale) {
|
|
168
|
+
* return api.savePreferences({ locale })
|
|
63
169
|
* },
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
* return response.json()
|
|
170
|
+
* error(_, error) {
|
|
171
|
+
* console.warn('Language not saved:', error)
|
|
67
172
|
* },
|
|
68
|
-
*
|
|
69
|
-
* entity.status = 'success'
|
|
70
|
-
* entity.todos = todos
|
|
71
|
-
* },
|
|
72
|
-
* error(entity, error) {
|
|
73
|
-
* entity.status = 'error'
|
|
74
|
-
* entity.error = error.message
|
|
75
|
-
* },
|
|
76
|
-
* finally(entity) {
|
|
77
|
-
* entity.lastFetched = Date.now()
|
|
78
|
-
* }
|
|
79
|
-
* })
|
|
173
|
+
* }),
|
|
80
174
|
* }
|
|
81
175
|
*
|
|
82
176
|
* // Trigger from UI
|
|
83
|
-
* api.notify('#
|
|
177
|
+
* api.notify('#preferences:localeSave', 'it')
|
|
84
178
|
*
|
|
85
179
|
* @example
|
|
86
180
|
* // With type scope - affects all entities of this type
|
|
@@ -99,40 +193,6 @@
|
|
|
99
193
|
*
|
|
100
194
|
* // Triggers sync for ALL counter entities
|
|
101
195
|
* api.notify('counter:sync')
|
|
102
|
-
*
|
|
103
|
-
* @example
|
|
104
|
-
* // Minimal - just run and success
|
|
105
|
-
* const user = {
|
|
106
|
-
* ...handleAsync('login', {
|
|
107
|
-
* async run({ username, password }, api) {
|
|
108
|
-
* const response = await fetch('/api/login', {
|
|
109
|
-
* method: 'POST',
|
|
110
|
-
* body: JSON.stringify({ username, password })
|
|
111
|
-
* })
|
|
112
|
-
* return response.json()
|
|
113
|
-
* },
|
|
114
|
-
* success(entity, user) {
|
|
115
|
-
* entity.currentUser = user
|
|
116
|
-
* entity.isAuthenticated = true
|
|
117
|
-
* }
|
|
118
|
-
* })
|
|
119
|
-
* }
|
|
120
|
-
*
|
|
121
|
-
* @example
|
|
122
|
-
* // Without start handler
|
|
123
|
-
* const data = {
|
|
124
|
-
* ...handleAsync('fetch', {
|
|
125
|
-
* async run(payload, api) {
|
|
126
|
-
* return fetch(`/api/data/${payload.id}`).then(r => r.json())
|
|
127
|
-
* },
|
|
128
|
-
* success(entity, result) {
|
|
129
|
-
* entity.data = result
|
|
130
|
-
* },
|
|
131
|
-
* error(entity, error) {
|
|
132
|
-
* console.error('Fetch failed:', error)
|
|
133
|
-
* }
|
|
134
|
-
* })
|
|
135
|
-
* }
|
|
136
196
|
*/
|
|
137
197
|
export function handleAsync(type, handlers, options = {}) {
|
|
138
198
|
const { scope = "entity" } = options
|
|
@@ -216,3 +276,7 @@ export function nextCallId() {
|
|
|
216
276
|
}
|
|
217
277
|
|
|
218
278
|
export const ASYNC_META = Symbol.for("@inglorious/store/asyncMeta")
|
|
279
|
+
|
|
280
|
+
function messageOf(error) {
|
|
281
|
+
return error instanceof Error ? error.message : String(error)
|
|
282
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
const RENDER = /^render/
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Keeps some of an entity's fields in storage, as a byproduct of the entity:
|
|
5
|
+
* the entity stays the one source of truth. When the entity is created, the
|
|
6
|
+
* fields come back from storage, before the type's own `create`, whose
|
|
7
|
+
* defaults (`entity.consent ??= null`) then keep them. After every handler,
|
|
8
|
+
* the fields are written back if they changed.
|
|
9
|
+
*
|
|
10
|
+
* Put it last in the type's array: it saves after the handlers before it.
|
|
11
|
+
* Storage that is missing, full or refusing, as in a private window, only
|
|
12
|
+
* means nothing is kept.
|
|
13
|
+
*
|
|
14
|
+
* @param {string[]} fields The entity's fields to keep.
|
|
15
|
+
* @param {Object} [options]
|
|
16
|
+
* @param {string | ((entity: Object) => string)} [options.key] Where the
|
|
17
|
+
* fields are kept. Defaults to the entity's id.
|
|
18
|
+
* @param {() => Storage | undefined} [options.storage] A Web Storage, such as
|
|
19
|
+
* `() => sessionStorage` for the tab only. Defaults to `localStorage`.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* const types = {
|
|
23
|
+
* Analytics: [createAnalytics({ adapter }), withStorage(["consent"])],
|
|
24
|
+
* Settings: [Settings, withStorage(["theme", "volume"], { key: "my-app" })],
|
|
25
|
+
* }
|
|
26
|
+
*/
|
|
27
|
+
export function withStorage(
|
|
28
|
+
fields,
|
|
29
|
+
{ key, storage = () => globalThis.localStorage } = {},
|
|
30
|
+
) {
|
|
31
|
+
const keyOf = (entity) =>
|
|
32
|
+
typeof key === "function" ? key(entity) : (key ?? entity.id)
|
|
33
|
+
|
|
34
|
+
return (type) => {
|
|
35
|
+
/** What is kept for each entity, as written. */
|
|
36
|
+
const kept = new Map()
|
|
37
|
+
|
|
38
|
+
function save(entity) {
|
|
39
|
+
if (!isEntity(entity)) return
|
|
40
|
+
const value = JSON.stringify(pick(entity, fields))
|
|
41
|
+
if (kept.get(entity.id) === value) return
|
|
42
|
+
kept.set(entity.id, value)
|
|
43
|
+
write(storage, keyOf(entity), value)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const behavior = {}
|
|
47
|
+
|
|
48
|
+
for (const [name, handler] of Object.entries(type)) {
|
|
49
|
+
if (typeof handler !== "function" || name === "create") continue
|
|
50
|
+
if (RENDER.test(name)) continue
|
|
51
|
+
behavior[name] = function (entity, payload, api) {
|
|
52
|
+
const result = handler.call(this, entity, payload, api)
|
|
53
|
+
save(entity)
|
|
54
|
+
return result
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
behavior.create = function (entity, payload, api) {
|
|
59
|
+
const stored = read(storage, keyOf(entity))
|
|
60
|
+
kept.set(entity.id, stored)
|
|
61
|
+
Object.assign(entity, pick(parse(stored), fields))
|
|
62
|
+
const result = type.create?.call(this, entity, payload, api)
|
|
63
|
+
save(entity)
|
|
64
|
+
return result
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return behavior
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function pick(source, fields) {
|
|
72
|
+
const picked = {}
|
|
73
|
+
for (const field of fields) {
|
|
74
|
+
if (source && field in source) picked[field] = source[field]
|
|
75
|
+
}
|
|
76
|
+
return picked
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isEntity(value) {
|
|
80
|
+
return Boolean(value) && typeof value === "object" && "id" in value
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function parse(stored) {
|
|
84
|
+
try {
|
|
85
|
+
return stored ? JSON.parse(stored) : null
|
|
86
|
+
} catch {
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function read(storage, key) {
|
|
92
|
+
try {
|
|
93
|
+
return storage()?.getItem(key) ?? null
|
|
94
|
+
} catch {
|
|
95
|
+
return null
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function write(storage, key, value) {
|
|
100
|
+
try {
|
|
101
|
+
storage()?.setItem(key, value)
|
|
102
|
+
} catch {
|
|
103
|
+
// Nothing is kept: the entity still has the value.
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -194,3 +194,66 @@ export function handleAsync<
|
|
|
194
194
|
handlers: AsyncHandlers<TEntity, TPayload, TResult, TApi>,
|
|
195
195
|
options?: AsyncOptions,
|
|
196
196
|
): AsyncEvents<TType, TEntity, TPayload, TResult, TApi>
|
|
197
|
+
|
|
198
|
+
/** Where a request is: `"loading"`, then `"success"` or `"error"`. */
|
|
199
|
+
export type RequestStatus = "loading" | "success" | "error"
|
|
200
|
+
|
|
201
|
+
export interface RequestOptions<TError = string> extends AsyncOptions {
|
|
202
|
+
/** The field for the status, when the entity has several requests. @default "status" */
|
|
203
|
+
status?: string
|
|
204
|
+
/** The field for the error. @default "error" */
|
|
205
|
+
error?: string
|
|
206
|
+
/** What to store as the error, such as a translation key. Defaults to its message. */
|
|
207
|
+
toError?: (error: unknown) => TError
|
|
208
|
+
/** Whether a call replaced by a newer one is ignored. @default true */
|
|
209
|
+
isLatestOnly?: boolean
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Handler functions for a request: those of `handleAsync`, whose `error`
|
|
214
|
+
* receives the error as `toError` turned it, after the entity's error field is
|
|
215
|
+
* set.
|
|
216
|
+
*/
|
|
217
|
+
export interface RequestHandlers<
|
|
218
|
+
TEntity extends BaseEntity = BaseEntity,
|
|
219
|
+
TPayload = any,
|
|
220
|
+
TResult = any,
|
|
221
|
+
TApi extends Api = Api,
|
|
222
|
+
TError = string,
|
|
223
|
+
> extends Omit<AsyncHandlers<TEntity, TPayload, TResult, TApi>, "error"> {
|
|
224
|
+
error?: (entity: TEntity, error: TError, api: TApi) => void
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The handlers of a request: a call whose progress the entity shows. The
|
|
229
|
+
* entity's `status` is `"loading"` from the start, then `"success"` or
|
|
230
|
+
* `"error"`, and its `error` holds what went wrong. Only the latest call
|
|
231
|
+
* counts: the answer of a call that a newer one replaced is dropped. Prefer it
|
|
232
|
+
* to `handleAsync` whenever the entity shows that something is happening.
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* ```typescript
|
|
236
|
+
* const JobList = {
|
|
237
|
+
* ...handleRequest("search", {
|
|
238
|
+
* run: (query: string) => searchJobs(query),
|
|
239
|
+
* success(entity, jobs) {
|
|
240
|
+
* entity.jobs = jobs
|
|
241
|
+
* },
|
|
242
|
+
* }),
|
|
243
|
+
* } satisfies EntityType<JobListEntity, AppApi>
|
|
244
|
+
*
|
|
245
|
+
* const types = { JobList: [JobList, withDebounce(300, ["search"])] }
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
export function handleRequest<
|
|
249
|
+
TEntity extends BaseEntity = BaseEntity,
|
|
250
|
+
TPayload = any,
|
|
251
|
+
TResult = any,
|
|
252
|
+
TApi extends Api = Api,
|
|
253
|
+
TType extends string = string,
|
|
254
|
+
TError = string,
|
|
255
|
+
>(
|
|
256
|
+
type: TType,
|
|
257
|
+
handlers: RequestHandlers<TEntity, TPayload, TResult, TApi, TError>,
|
|
258
|
+
options?: RequestOptions<TError>,
|
|
259
|
+
): AsyncEvents<TType, TEntity, TPayload, TResult, TApi>
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Api } from "../api"
|
|
2
|
+
import { BaseEntity, EntityType } from "../store"
|
|
3
|
+
|
|
4
|
+
export interface StorageOptions {
|
|
5
|
+
/** Where the fields are kept. Defaults to the entity's id. */
|
|
6
|
+
key?: string | ((entity: BaseEntity & { id: string }) => string)
|
|
7
|
+
/** A Web Storage, such as `() => sessionStorage`. Defaults to `localStorage`. */
|
|
8
|
+
storage?: () => Storage | undefined
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Keeps some of an entity's fields in storage, as a byproduct of the entity,
|
|
13
|
+
* which stays the one source of truth: they come back when it is created,
|
|
14
|
+
* before the type's own `create`, and are written back after any handler that
|
|
15
|
+
* changes them. Put it last in the type's array.
|
|
16
|
+
*/
|
|
17
|
+
export declare function withStorage(
|
|
18
|
+
fields: string[],
|
|
19
|
+
options?: StorageOptions,
|
|
20
|
+
): <TEntity extends BaseEntity, TApi extends Api>(
|
|
21
|
+
type: EntityType<TEntity, TApi>,
|
|
22
|
+
) => EntityType<TEntity, TApi>
|