@inglorious/store 12.3.0 → 12.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/README.md +52 -0
- package/package.json +8 -8
- package/src/behaviors/async.js +130 -66
- package/types/behaviors/async.d.ts +63 -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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/store",
|
|
3
|
-
"version": "12.
|
|
3
|
+
"version": "12.4.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",
|
|
@@ -75,19 +75,19 @@
|
|
|
75
75
|
},
|
|
76
76
|
"sideEffects": false,
|
|
77
77
|
"dependencies": {
|
|
78
|
-
"mutative": "^
|
|
78
|
+
"mutative": "^2.0.2"
|
|
79
79
|
},
|
|
80
80
|
"peerDependencies": {
|
|
81
|
-
"@inglorious/utils": "^5.
|
|
81
|
+
"@inglorious/utils": "^5.3.0"
|
|
82
82
|
},
|
|
83
83
|
"devDependencies": {
|
|
84
84
|
"@inglorious/eslint-config": "1.2.0",
|
|
85
|
-
"@inglorious/utils": "5.
|
|
86
|
-
"@reduxjs/toolkit": "^2.
|
|
87
|
-
"prettier": "^3.9.
|
|
85
|
+
"@inglorious/utils": "5.3.0",
|
|
86
|
+
"@reduxjs/toolkit": "^2.14.0",
|
|
87
|
+
"prettier": "^3.9.10",
|
|
88
88
|
"typescript": "~7.0.2",
|
|
89
|
-
"vite": "^8.
|
|
90
|
-
"vitest": "^5.
|
|
89
|
+
"vite": "^8.3.7",
|
|
90
|
+
"vitest": "^5.1.0"
|
|
91
91
|
},
|
|
92
92
|
"engines": {
|
|
93
93
|
"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
|
+
}
|
|
@@ -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>
|