@hyper-fetch/react 9.8.1 → 10.0.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 +24 -26
- package/__tests__/features/use-listener/use-listener.payload.spec.tsx +196 -0
- package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +22 -1
- package/__tests__/features/use-listener/use-listener.status.spec.tsx +288 -0
- package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts +10 -3
- package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.hooks.d.ts +20 -4
- package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.types.d.ts +11 -0
- package/dist/hooks/use-listener/use-listener.types.d.ts.map +1 -1
- package/dist/index.mjs +66 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-socket-state/use-socket-state.hooks.ts +36 -11
- package/src/hooks/use-listener/use-listener.hooks.ts +66 -13
- package/src/hooks/use-listener/use-listener.types.ts +12 -0
package/README.md
CHANGED
|
@@ -170,39 +170,35 @@ const UserPosts = ({ userId }: { userId: number }) => {
|
|
|
170
170
|
```tsx
|
|
171
171
|
import { useSubmit } from "@hyper-fetch/react";
|
|
172
172
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
rollback: () => client.cache.set(cacheKey, previous),
|
|
190
|
-
// On success, refetch to get the real server data
|
|
191
|
-
invalidate: [cacheKey],
|
|
192
|
-
};
|
|
193
|
-
});
|
|
173
|
+
// setOptimistic runs before the request is sent - the comment list updates instantly
|
|
174
|
+
const addCommentOptimistic = addComment.setOptimistic(({ params, payload, optimistic }) => {
|
|
175
|
+
const temp = { id: `temp-${Date.now()}`, text: payload.text, author: "You" };
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
updates: [
|
|
179
|
+
optimistic(getComments.setParams({ postId: params.postId }))
|
|
180
|
+
.insert(temp)
|
|
181
|
+
// On success swap the temporary comment for the one returned by the server
|
|
182
|
+
.commit(({ data, response }) => data.map((comment) => (comment.id === temp.id ? response.data : comment)))
|
|
183
|
+
// If the request fails, take it out again
|
|
184
|
+
.rollback(({ data }) => data.filter((comment) => comment.id !== temp.id)),
|
|
185
|
+
],
|
|
186
|
+
context: { tempId: temp.id },
|
|
187
|
+
};
|
|
188
|
+
});
|
|
194
189
|
|
|
195
|
-
|
|
190
|
+
const AddComment = ({ postId }: { postId: number }) => {
|
|
191
|
+
const { submit, submitting, onSubmitError } = useSubmit(addCommentOptimistic);
|
|
196
192
|
|
|
197
|
-
// mutationContext is
|
|
193
|
+
// mutationContext is typed from the context returned by setOptimistic
|
|
198
194
|
onSubmitError(({ mutationContext }) => {
|
|
199
|
-
console.log("Rolled back
|
|
195
|
+
console.log("Rolled back comment", mutationContext?.tempId);
|
|
200
196
|
});
|
|
201
197
|
|
|
202
198
|
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
|
203
199
|
e.preventDefault();
|
|
204
200
|
const text = new FormData(e.currentTarget).get("text") as string;
|
|
205
|
-
submit({
|
|
201
|
+
submit({ params: { postId }, payload: { text } });
|
|
206
202
|
e.currentTarget.reset();
|
|
207
203
|
};
|
|
208
204
|
|
|
@@ -217,6 +213,8 @@ const AddComment = ({ postId }: { postId: number }) => {
|
|
|
217
213
|
};
|
|
218
214
|
```
|
|
219
215
|
|
|
216
|
+
The comment list is refreshed from the server once the request settles.
|
|
217
|
+
|
|
220
218
|
## License
|
|
221
219
|
|
|
222
|
-
[
|
|
220
|
+
[Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import type { ListenerCallbackType, ListenerOfAdapter } from "@hyper-fetch/sockets";
|
|
2
|
+
import { Socket, SocketAdapter } from "@hyper-fetch/sockets";
|
|
3
|
+
import { act, render, renderHook, screen } from "@testing-library/react";
|
|
4
|
+
import { useListener } from "hooks/use-listener";
|
|
5
|
+
import React, { StrictMode, useState } from "react";
|
|
6
|
+
|
|
7
|
+
type Message = { text: string };
|
|
8
|
+
type RoomInput = { roomId: string };
|
|
9
|
+
|
|
10
|
+
type Subscription = {
|
|
11
|
+
listener: ListenerOfAdapter<any>;
|
|
12
|
+
callback: ListenerCallbackType<any, any>;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Adapter with one server subscription per (topic, payload), like the tRPC and oRPC socket adapters */
|
|
16
|
+
const createPayloadSocket = () => {
|
|
17
|
+
const subscriptions: Subscription[] = [];
|
|
18
|
+
let onEvent:
|
|
19
|
+
| ((event: { topic: string; data: unknown; extra: undefined; callbacks?: ReadonlySet<any> }) => void)
|
|
20
|
+
| null = null;
|
|
21
|
+
|
|
22
|
+
const adapter = new SocketAdapter({ name: "payload-test", defaultConnected: true }).setConnector((bindings) => {
|
|
23
|
+
({ onEvent } = bindings);
|
|
24
|
+
return {
|
|
25
|
+
connect: () => {},
|
|
26
|
+
reconnect: () => {},
|
|
27
|
+
disconnect: () => {},
|
|
28
|
+
emit: () => {},
|
|
29
|
+
listen: (listener, callback) => {
|
|
30
|
+
const subscription = { listener, callback };
|
|
31
|
+
subscriptions.push(subscription);
|
|
32
|
+
return bindings.onListen({
|
|
33
|
+
listener,
|
|
34
|
+
callback,
|
|
35
|
+
onUnmount: () => subscriptions.splice(subscriptions.indexOf(subscription), 1),
|
|
36
|
+
});
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const socket = new Socket({ url: "ws://payload", adapter });
|
|
42
|
+
|
|
43
|
+
const serverPush = (payload: RoomInput, data: Message) => {
|
|
44
|
+
const key = JSON.stringify(payload);
|
|
45
|
+
const callbacks = new Set(
|
|
46
|
+
subscriptions.filter((sub) => JSON.stringify(sub.listener.payload) === key).map((sub) => sub.callback),
|
|
47
|
+
);
|
|
48
|
+
act(() => {
|
|
49
|
+
onEvent?.({ topic: "chat.onMessage", data, extra: undefined, callbacks });
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const payloads = () => subscriptions.map((sub) => sub.listener.payload);
|
|
54
|
+
|
|
55
|
+
return { socket, subscriptions, serverPush, payloads };
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
describe("useListener [ Payload ]", () => {
|
|
59
|
+
let setup: ReturnType<typeof createPayloadSocket>;
|
|
60
|
+
let onMessage: ReturnType<typeof createOnMessage>;
|
|
61
|
+
|
|
62
|
+
const createOnMessage = (socket: ReturnType<typeof createPayloadSocket>["socket"]) =>
|
|
63
|
+
socket.createListener<Message, RoomInput>()({ topic: "chat.onMessage" });
|
|
64
|
+
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
setup = createPayloadSocket();
|
|
67
|
+
onMessage = createOnMessage(setup.socket);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("should subscribe with the payload of the listener", () => {
|
|
71
|
+
renderHook(() => useListener(onMessage.setPayload({ roomId: "1" })));
|
|
72
|
+
|
|
73
|
+
expect(setup.payloads()).toStrictEqual([{ roomId: "1" }]);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("should receive only the messages of its payload", () => {
|
|
77
|
+
const view = renderHook(() => useListener(onMessage.setPayload({ roomId: "1" })));
|
|
78
|
+
|
|
79
|
+
setup.serverPush({ roomId: "2" }, { text: "other room" });
|
|
80
|
+
expect(view.result.current.data).toBeNull();
|
|
81
|
+
|
|
82
|
+
setup.serverPush({ roomId: "1" }, { text: "my room" });
|
|
83
|
+
expect(view.result.current.data).toStrictEqual({ text: "my room" });
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("should keep the subscription when an equal payload is created on every render", () => {
|
|
87
|
+
const view = renderHook(() => useListener(onMessage.setPayload({ roomId: "1" })));
|
|
88
|
+
|
|
89
|
+
view.rerender();
|
|
90
|
+
view.rerender();
|
|
91
|
+
|
|
92
|
+
expect(setup.subscriptions).toHaveLength(1);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("should move the subscription when the payload changes", () => {
|
|
96
|
+
const view = renderHook(({ roomId }) => useListener(onMessage.setPayload({ roomId })), {
|
|
97
|
+
initialProps: { roomId: "1" },
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
view.rerender({ roomId: "2" });
|
|
101
|
+
|
|
102
|
+
expect(setup.payloads()).toStrictEqual([{ roomId: "2" }]);
|
|
103
|
+
setup.serverPush({ roomId: "1" }, { text: "old room" });
|
|
104
|
+
expect(view.result.current.data).toBeNull();
|
|
105
|
+
setup.serverPush({ roomId: "2" }, { text: "new room" });
|
|
106
|
+
expect(view.result.current.data).toStrictEqual({ text: "new room" });
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("should unsubscribe on unmount", () => {
|
|
110
|
+
const view = renderHook(() => useListener(onMessage.setPayload({ roomId: "1" })));
|
|
111
|
+
|
|
112
|
+
view.unmount();
|
|
113
|
+
|
|
114
|
+
expect(setup.subscriptions).toHaveLength(0);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("should route messages between components listening with different payloads", () => {
|
|
118
|
+
const Room = ({ roomId }: { roomId: string }) => {
|
|
119
|
+
const { data } = useListener(onMessage.setPayload({ roomId }));
|
|
120
|
+
return <div data-testid={`room-${roomId}`}>{data?.text ?? "empty"}</div>;
|
|
121
|
+
};
|
|
122
|
+
render(
|
|
123
|
+
<>
|
|
124
|
+
<Room roomId="1" />
|
|
125
|
+
<Room roomId="2" />
|
|
126
|
+
</>,
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
setup.serverPush({ roomId: "2" }, { text: "second" });
|
|
130
|
+
|
|
131
|
+
expect(screen.getByTestId("room-1").textContent).toBe("empty");
|
|
132
|
+
expect(screen.getByTestId("room-2").textContent).toBe("second");
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("should switch rooms from a state change", () => {
|
|
136
|
+
let setRoom: (roomId: string) => void = () => {};
|
|
137
|
+
const Room = () => {
|
|
138
|
+
const [roomId, setRoomId] = useState("1");
|
|
139
|
+
setRoom = setRoomId;
|
|
140
|
+
const { data } = useListener(onMessage.setPayload({ roomId }));
|
|
141
|
+
return <div data-testid="room">{data?.text ?? "empty"}</div>;
|
|
142
|
+
};
|
|
143
|
+
render(<Room />);
|
|
144
|
+
|
|
145
|
+
act(() => setRoom("2"));
|
|
146
|
+
setup.serverPush({ roomId: "2" }, { text: "switched" });
|
|
147
|
+
|
|
148
|
+
expect(screen.getByTestId("room").textContent).toBe("switched");
|
|
149
|
+
expect(setup.payloads()).toStrictEqual([{ roomId: "2" }]);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
describe("When rendered in StrictMode", () => {
|
|
153
|
+
it("should hold a single subscription", () => {
|
|
154
|
+
renderHook(() => useListener(onMessage.setPayload({ roomId: "1" })), { wrapper: StrictMode });
|
|
155
|
+
|
|
156
|
+
expect(setup.subscriptions).toHaveLength(1);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("should hold a single subscription after the payload changes", () => {
|
|
160
|
+
const view = renderHook(({ roomId }) => useListener(onMessage.setPayload({ roomId })), {
|
|
161
|
+
initialProps: { roomId: "1" },
|
|
162
|
+
wrapper: StrictMode,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
view.rerender({ roomId: "2" });
|
|
166
|
+
|
|
167
|
+
expect(setup.payloads()).toStrictEqual([{ roomId: "2" }]);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("should leave no subscription after unmount", () => {
|
|
171
|
+
const view = renderHook(() => useListener(onMessage.setPayload({ roomId: "1" })), { wrapper: StrictMode });
|
|
172
|
+
|
|
173
|
+
view.unmount();
|
|
174
|
+
|
|
175
|
+
expect(setup.subscriptions).toHaveLength(0);
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe("When typing", () => {
|
|
180
|
+
it("should reject a listener without its required payload", () => {
|
|
181
|
+
const useMissing = () =>
|
|
182
|
+
// @ts-expect-error the payload is required
|
|
183
|
+
useListener(onMessage);
|
|
184
|
+
const useSet = () => useListener(onMessage.setPayload({ roomId: "1" }));
|
|
185
|
+
expectTypeOf(useSet).returns.toHaveProperty("data").toEqualTypeOf<Message | null>();
|
|
186
|
+
expect(useMissing).toBeFunction();
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it("should accept a listener without a payload", () => {
|
|
190
|
+
const plain = setup.socket.createListener<Message>()({ topic: "news" });
|
|
191
|
+
const usePlain = () => useListener(plain);
|
|
192
|
+
expectTypeOf(usePlain).returns.toHaveProperty("data").toEqualTypeOf<Message | null>();
|
|
193
|
+
expect(true).toBeTrue();
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
});
|
|
@@ -11,7 +11,8 @@ describe("useListener & useEmitter [ SSR ]", () => {
|
|
|
11
11
|
let socket: Socket;
|
|
12
12
|
|
|
13
13
|
beforeEach(() => {
|
|
14
|
-
socket
|
|
14
|
+
// Node has a global WebSocket, so a socket created on the server connects - SSR apps turn it off there
|
|
15
|
+
socket = new Socket({ url: "ws://ssr", adapterOptions: { autoConnect: false } });
|
|
15
16
|
socket.onError(() => null);
|
|
16
17
|
});
|
|
17
18
|
|
|
@@ -23,6 +24,26 @@ describe("useListener & useEmitter [ SSR ]", () => {
|
|
|
23
24
|
expect(typeof window).toBe("undefined");
|
|
24
25
|
});
|
|
25
26
|
|
|
27
|
+
it("should report the connection of a socket that auto connects on the server", async () => {
|
|
28
|
+
const connecting = new Socket({ url: "ws://ssr-connecting" });
|
|
29
|
+
connecting.onError(() => null);
|
|
30
|
+
const listener = connecting.createListener<Message>()({ topic: "chat" });
|
|
31
|
+
const Component = () => {
|
|
32
|
+
const { connected, connecting: isConnecting } = useListener(listener);
|
|
33
|
+
return (
|
|
34
|
+
<p>
|
|
35
|
+
{String(connected)}|{String(isConnecting)}
|
|
36
|
+
</p>
|
|
37
|
+
);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const html = renderToString(<Component />);
|
|
41
|
+
|
|
42
|
+
expect(typeof globalThis.WebSocket).toBe("function");
|
|
43
|
+
expect(html.replaceAll("<!-- -->", "")).toBe("<p>false|true</p>");
|
|
44
|
+
await connecting.destroy();
|
|
45
|
+
});
|
|
46
|
+
|
|
26
47
|
it("should render useListener on the server with the empty state", () => {
|
|
27
48
|
const listener = socket.createListener<Message>()({ topic: "chat" });
|
|
28
49
|
const Component = () => {
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import type { ListenerCallbackType, ListenerOfAdapter } from "@hyper-fetch/sockets";
|
|
2
|
+
import { Socket, SocketAdapter } from "@hyper-fetch/sockets";
|
|
3
|
+
import { act, renderHook } from "@testing-library/react";
|
|
4
|
+
import { useListener } from "hooks/use-listener";
|
|
5
|
+
import React, { StrictMode } from "react";
|
|
6
|
+
import { renderToString } from "react-dom/server";
|
|
7
|
+
|
|
8
|
+
type Message = { text: string };
|
|
9
|
+
type RoomInput = { roomId: string };
|
|
10
|
+
|
|
11
|
+
type Subscription = {
|
|
12
|
+
listener: ListenerOfAdapter<any>;
|
|
13
|
+
callback: ListenerCallbackType<any, any>;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Adapter whose server confirms and ends subscriptions on demand, like the tRPC and oRPC socket adapters */
|
|
17
|
+
const createConfirmingSocket = () => {
|
|
18
|
+
const subscriptions: Subscription[] = [];
|
|
19
|
+
const adapter = new SocketAdapter({ name: "confirming", defaultConnected: true, confirmsSubscriptions: true });
|
|
20
|
+
type Bindings = Parameters<Parameters<typeof adapter.setConnector>[0]>[0];
|
|
21
|
+
let bindings: Bindings | undefined;
|
|
22
|
+
|
|
23
|
+
adapter.setConnector((connectorBindings) => {
|
|
24
|
+
bindings = connectorBindings;
|
|
25
|
+
return {
|
|
26
|
+
connect: () => {},
|
|
27
|
+
reconnect: () => {},
|
|
28
|
+
disconnect: () => {},
|
|
29
|
+
emit: () => {},
|
|
30
|
+
listen: (listener, callback) => {
|
|
31
|
+
const subscription = { listener, callback };
|
|
32
|
+
subscriptions.push(subscription);
|
|
33
|
+
return connectorBindings.onListen({
|
|
34
|
+
listener,
|
|
35
|
+
callback,
|
|
36
|
+
onUnmount: () => subscriptions.splice(subscriptions.indexOf(subscription), 1),
|
|
37
|
+
});
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const socket = new Socket({ url: "ws://confirming", adapter });
|
|
43
|
+
const callbacksOf = (payload: RoomInput) =>
|
|
44
|
+
new Set(
|
|
45
|
+
subscriptions
|
|
46
|
+
.filter((sub) => JSON.stringify(sub.listener.payload) === JSON.stringify(payload))
|
|
47
|
+
.map((sub) => sub.callback),
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
const server = {
|
|
51
|
+
start: (payload: RoomInput) =>
|
|
52
|
+
act(() => bindings?.onListenerStart({ topic: "chat.onMessage", callbacks: callbacksOf(payload) })),
|
|
53
|
+
push: (payload: RoomInput, data: Message) =>
|
|
54
|
+
act(() =>
|
|
55
|
+
bindings?.onEvent({ topic: "chat.onMessage", data, extra: undefined, callbacks: callbacksOf(payload) }),
|
|
56
|
+
),
|
|
57
|
+
end: (payload: RoomInput, error: Error | null = null) =>
|
|
58
|
+
act(() => bindings?.onListenerEnd({ topic: "chat.onMessage", callbacks: callbacksOf(payload), error })),
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const onMessage = socket.createListener<Message, RoomInput>()({ topic: "chat.onMessage" });
|
|
62
|
+
|
|
63
|
+
return { socket, subscriptions, server, onMessage };
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Reading the state after the events needs every key tracked, like in the other hook specs */
|
|
67
|
+
const untracked = { dependencyTracking: false };
|
|
68
|
+
|
|
69
|
+
describe("useListener [ Status ]", () => {
|
|
70
|
+
let setup: ReturnType<typeof createConfirmingSocket>;
|
|
71
|
+
|
|
72
|
+
beforeEach(() => {
|
|
73
|
+
setup = createConfirmingSocket();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
describe("When the adapter does not confirm subscriptions", () => {
|
|
77
|
+
it("should be listening right after the mount", () => {
|
|
78
|
+
const socket = new Socket({ url: "ws://plain", adapterOptions: { autoConnect: false } });
|
|
79
|
+
const listener = socket.createListener<Message>()({ topic: "news" });
|
|
80
|
+
const view = renderHook(() => useListener(listener, untracked));
|
|
81
|
+
|
|
82
|
+
expect(view.result.current.status).toBe("listening");
|
|
83
|
+
expect(view.result.current.error).toBeNull();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("should be idle when rendered on the server", () => {
|
|
87
|
+
const socket = new Socket({ url: "ws://plain", adapterOptions: { autoConnect: false } });
|
|
88
|
+
const listener = socket.createListener<Message>()({ topic: "news" });
|
|
89
|
+
let status = "";
|
|
90
|
+
const Component = () => {
|
|
91
|
+
({ status } = useListener(listener));
|
|
92
|
+
return null;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
renderToString(<Component />);
|
|
96
|
+
|
|
97
|
+
expect(status).toBe("idle");
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
describe("When the server confirms the subscription", () => {
|
|
102
|
+
it("should be starting until the server confirms it", () => {
|
|
103
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked));
|
|
104
|
+
|
|
105
|
+
expect(view.result.current.status).toBe("starting");
|
|
106
|
+
|
|
107
|
+
setup.server.start({ roomId: "1" });
|
|
108
|
+
|
|
109
|
+
expect(view.result.current.status).toBe("listening");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("should call onStart with the topic", () => {
|
|
113
|
+
const onStart = vi.fn();
|
|
114
|
+
renderHook(() => {
|
|
115
|
+
const result = useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked);
|
|
116
|
+
result.onStart(onStart);
|
|
117
|
+
return result;
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
setup.server.start({ roomId: "1" });
|
|
121
|
+
|
|
122
|
+
expect(onStart).toHaveBeenCalledWith({ topic: "chat.onMessage" });
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("should be starting again after the payload changes", () => {
|
|
126
|
+
const view = renderHook(({ roomId }) => useListener(setup.onMessage.setPayload({ roomId }), untracked), {
|
|
127
|
+
initialProps: { roomId: "1" },
|
|
128
|
+
});
|
|
129
|
+
setup.server.start({ roomId: "1" });
|
|
130
|
+
|
|
131
|
+
view.rerender({ roomId: "2" });
|
|
132
|
+
|
|
133
|
+
expect(view.result.current.status).toBe("starting");
|
|
134
|
+
setup.server.start({ roomId: "2" });
|
|
135
|
+
expect(view.result.current.status).toBe("listening");
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe("When the server ends the subscription", () => {
|
|
140
|
+
it("should be ended without an error when it finished", () => {
|
|
141
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked));
|
|
142
|
+
setup.server.start({ roomId: "1" });
|
|
143
|
+
|
|
144
|
+
setup.server.end({ roomId: "1" });
|
|
145
|
+
|
|
146
|
+
expect(view.result.current.status).toBe("ended");
|
|
147
|
+
expect(view.result.current.error).toBeNull();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("should be failed with the error when it failed", () => {
|
|
151
|
+
const error = new Error("Forbidden");
|
|
152
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked));
|
|
153
|
+
|
|
154
|
+
setup.server.end({ roomId: "1" }, error);
|
|
155
|
+
|
|
156
|
+
expect(view.result.current.status).toBe("failed");
|
|
157
|
+
expect(view.result.current.error).toBe(error);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it("should keep the last data after the end", () => {
|
|
161
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked));
|
|
162
|
+
setup.server.push({ roomId: "1" }, { text: "last" });
|
|
163
|
+
|
|
164
|
+
setup.server.end({ roomId: "1" });
|
|
165
|
+
|
|
166
|
+
expect(view.result.current.data).toStrictEqual({ text: "last" });
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("should stop listening after the end", () => {
|
|
170
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked));
|
|
171
|
+
|
|
172
|
+
setup.server.end({ roomId: "1" });
|
|
173
|
+
|
|
174
|
+
expect(setup.subscriptions).toHaveLength(0);
|
|
175
|
+
setup.server.push({ roomId: "1" }, { text: "late" });
|
|
176
|
+
expect(view.result.current.data).toBeNull();
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("should call onEnd with the error", () => {
|
|
180
|
+
const onEnd = vi.fn();
|
|
181
|
+
const error = new Error("Gone");
|
|
182
|
+
renderHook(() => {
|
|
183
|
+
const result = useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked);
|
|
184
|
+
result.onEnd(onEnd);
|
|
185
|
+
return result;
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
setup.server.end({ roomId: "1" }, error);
|
|
189
|
+
|
|
190
|
+
expect(onEnd).toHaveBeenCalledWith({ topic: "chat.onMessage", error });
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it("should subscribe again with listen and clear the error", () => {
|
|
194
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked));
|
|
195
|
+
setup.server.end({ roomId: "1" }, new Error("Gone"));
|
|
196
|
+
|
|
197
|
+
act(() => view.result.current.listen());
|
|
198
|
+
|
|
199
|
+
expect(view.result.current.status).toBe("starting");
|
|
200
|
+
expect(view.result.current.error).toBeNull();
|
|
201
|
+
expect(setup.subscriptions).toHaveLength(1);
|
|
202
|
+
setup.server.start({ roomId: "1" });
|
|
203
|
+
setup.server.push({ roomId: "1" }, { text: "back" });
|
|
204
|
+
expect(view.result.current.status).toBe("listening");
|
|
205
|
+
expect(view.result.current.data).toStrictEqual({ text: "back" });
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it("should subscribe again when the payload changes after the end", () => {
|
|
209
|
+
const view = renderHook(({ roomId }) => useListener(setup.onMessage.setPayload({ roomId }), untracked), {
|
|
210
|
+
initialProps: { roomId: "1" },
|
|
211
|
+
});
|
|
212
|
+
setup.server.end({ roomId: "1" });
|
|
213
|
+
|
|
214
|
+
view.rerender({ roomId: "2" });
|
|
215
|
+
|
|
216
|
+
expect(view.result.current.status).toBe("starting");
|
|
217
|
+
expect(setup.subscriptions.map((sub) => sub.listener.payload)).toStrictEqual([{ roomId: "2" }]);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("should not change the status when an old subscription ends after the payload changed", () => {
|
|
221
|
+
const view = renderHook(({ roomId }) => useListener(setup.onMessage.setPayload({ roomId }), untracked), {
|
|
222
|
+
initialProps: { roomId: "1" },
|
|
223
|
+
});
|
|
224
|
+
view.rerender({ roomId: "2" });
|
|
225
|
+
setup.server.start({ roomId: "2" });
|
|
226
|
+
|
|
227
|
+
setup.server.end({ roomId: "1" });
|
|
228
|
+
|
|
229
|
+
expect(view.result.current.status).toBe("listening");
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
describe("When rendered in StrictMode", () => {
|
|
234
|
+
it("should hold one subscription and follow its status", () => {
|
|
235
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" }), untracked), {
|
|
236
|
+
wrapper: StrictMode,
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
expect(setup.subscriptions).toHaveLength(1);
|
|
240
|
+
setup.server.start({ roomId: "1" });
|
|
241
|
+
expect(view.result.current.status).toBe("listening");
|
|
242
|
+
setup.server.end({ roomId: "1" });
|
|
243
|
+
expect(view.result.current.status).toBe("ended");
|
|
244
|
+
expect(setup.subscriptions).toHaveLength(0);
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
describe("When tracking dependencies", () => {
|
|
249
|
+
it("should not re-render for the status when the component does not read it", () => {
|
|
250
|
+
let renders = 0;
|
|
251
|
+
renderHook(() => {
|
|
252
|
+
renders += 1;
|
|
253
|
+
const { data } = useListener(setup.onMessage.setPayload({ roomId: "1" }));
|
|
254
|
+
return data;
|
|
255
|
+
});
|
|
256
|
+
const before = renders;
|
|
257
|
+
|
|
258
|
+
setup.server.start({ roomId: "1" });
|
|
259
|
+
setup.server.end({ roomId: "1" });
|
|
260
|
+
|
|
261
|
+
expect(renders).toBe(before);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it("should re-render for the status when the component reads it", () => {
|
|
265
|
+
const statuses: string[] = [];
|
|
266
|
+
renderHook(() => {
|
|
267
|
+
const { status } = useListener(setup.onMessage.setPayload({ roomId: "1" }));
|
|
268
|
+
statuses.push(status);
|
|
269
|
+
return status;
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
setup.server.start({ roomId: "1" });
|
|
273
|
+
setup.server.end({ roomId: "1" }, new Error("Gone"));
|
|
274
|
+
|
|
275
|
+
expect(statuses.at(-1)).toBe("failed");
|
|
276
|
+
expect(statuses).toContain("listening");
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
describe("When typing", () => {
|
|
281
|
+
it("should type the status and the error", () => {
|
|
282
|
+
const view = renderHook(() => useListener(setup.onMessage.setPayload({ roomId: "1" })));
|
|
283
|
+
expectTypeOf(view.result.current.status).toEqualTypeOf<"idle" | "starting" | "listening" | "ended" | "failed">();
|
|
284
|
+
expectTypeOf(view.result.current.error).toEqualTypeOf<Error | null>();
|
|
285
|
+
expect(true).toBeTrue();
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
});
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { SocketInstance, ExtractSocketExtraType } from '@hyper-fetch/sockets';
|
|
2
2
|
import { UseSocketStateType, UseSocketStateProps } from '..';
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Tracked socket state shared by the socket hooks. `extendedState` adds hook-specific fields (e.g. the listener
|
|
5
|
+
* status) that are tracked the same way and changed with `actions.setExtendedState`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const useSocketState: <DataType, Socket extends SocketInstance, ExtendedState extends Record<string, unknown> = Record<never, never>>(socket: Socket, { dependencyTracking, extendedState }: UseSocketStateProps & {
|
|
8
|
+
extendedState?: ExtendedState;
|
|
9
|
+
}) => readonly [UseSocketStateType<Socket, DataType> & ExtendedState, {
|
|
4
10
|
setData: (data: DataType | null) => void;
|
|
5
11
|
setExtra: (extra: ExtractSocketExtraType<Socket> | null) => void;
|
|
6
12
|
setConnected: (connected: boolean) => void;
|
|
@@ -19,8 +25,9 @@ export declare const useSocketState: <DataType, Socket extends SocketInstance>(s
|
|
|
19
25
|
attempts: number;
|
|
20
26
|
}) => void) => void;
|
|
21
27
|
}, {
|
|
22
|
-
readonly setRenderKey: (renderKey: keyof UseSocketStateType<Socket, DataType>) => void;
|
|
23
|
-
readonly getState: () => UseSocketStateType<Socket, DataType
|
|
28
|
+
readonly setRenderKey: (renderKey: keyof UseSocketStateType<Socket, DataType> | keyof ExtendedState) => void;
|
|
29
|
+
readonly getState: () => UseSocketStateType<Socket, DataType> & ExtendedState;
|
|
24
30
|
readonly rerender: () => void;
|
|
31
|
+
readonly setExtendedState: (newState: Partial<ExtendedState>) => void;
|
|
25
32
|
}];
|
|
26
33
|
//# sourceMappingURL=use-socket-state.hooks.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-socket-state.hooks.d.ts","sourceRoot":"","sources":["../../../src/helpers/use-socket-state/use-socket-state.hooks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAGvE,eAAO,MAAM,cAAc,
|
|
1
|
+
{"version":3,"file":"use-socket-state.hooks.d.ts","sourceRoot":"","sources":["../../../src/helpers/use-socket-state/use-socket-state.hooks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAGvE;;;GAGG;AACH,eAAO,MAAM,cAAc,GACzB,QAAQ,EACR,MAAM,SAAS,cAAc,EAC7B,aAAa,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAEpE,QAAQ,MAAM,EACd,uCAAuC,mBAAmB,GAAG;IAAE,aAAa,CAAC,EAAE,aAAa,CAAA;CAAE;oBAoF5E,QAAQ,GAAG,IAAI;sBAIb,sBAAsB,CAAC,MAAM,CAAC,GAAG,IAAI;8BAI7B,OAAO;gCAIL,OAAO;8BAIT,MAAM,GAAG,IAAI;;;4BAkBf,YAAY;+BAGT,YAAY;cAG7B,SAAS,oBAAoB,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI;6BAGxC,YAAY;+BAGV,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI;qCAG9B,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI;;;;;0CAwDnC,OAAO,CAAC,aAAa,CAAC;EAW3D,CAAC"}
|
|
@@ -1,12 +1,25 @@
|
|
|
1
|
-
import { ListenerInstance,
|
|
2
|
-
import { UseListenerOptionsType } from '.';
|
|
3
|
-
/**
|
|
4
|
-
|
|
1
|
+
import { ExtractListenerDeliveredType, ListenerEndType, ListenerInstance, ListenerRequiresPayload } from '@hyper-fetch/sockets';
|
|
2
|
+
import { ListenerStatusType, UseListenerOptionsType } from '.';
|
|
3
|
+
/** A listener whose subscription payload is required has to get it with `setPayload()` before it is passed */
|
|
4
|
+
type ListenerWithPayloadType<ListenerType extends ListenerInstance> = ListenerRequiresPayload<ListenerType> extends true ? ListenerType & {
|
|
5
|
+
"Set the payload with setPayload() before passing the listener": never;
|
|
6
|
+
} : ListenerType;
|
|
7
|
+
/**
|
|
8
|
+
* Subscribe to incoming socket messages on a given listener topic with tracked connection state and callbacks.
|
|
9
|
+
* Changing the topic params, payload, options, delivery or socket of the listener starts a new subscription.
|
|
10
|
+
*/
|
|
11
|
+
export declare const useListener: <ListenerType extends ListenerInstance, TSelected = ExtractListenerDeliveredType<ListenerType>>(listener: ListenerWithPayloadType<ListenerType>, options?: UseListenerOptionsType<ExtractListenerDeliveredType<ListenerType>, TSelected>) => {
|
|
5
12
|
listen: () => void;
|
|
6
13
|
onEvent: (callback: NonNullable<((response: {
|
|
7
14
|
data: ExtractListenerDeliveredType<ListenerType>;
|
|
8
15
|
extra: Record<string, any>;
|
|
9
16
|
}) => void) | null>) => void;
|
|
17
|
+
/** The subscription started - with tRPC and oRPC when the server confirmed it, also after a reconnect */
|
|
18
|
+
onStart: (callback: NonNullable<((data: {
|
|
19
|
+
topic: string;
|
|
20
|
+
}) => void) | null>) => void;
|
|
21
|
+
/** The server ended the subscription, with `error` when it failed */
|
|
22
|
+
onEnd: (callback: NonNullable<((data: ListenerEndType) => void) | null>) => void;
|
|
10
23
|
onConnected: (callback: VoidFunction) => void;
|
|
11
24
|
onDisconnected: (callback: VoidFunction) => void;
|
|
12
25
|
onError: <ErrorType = Event>(callback: (event: ErrorType) => void) => void;
|
|
@@ -28,5 +41,8 @@ export declare const useListener: <ListenerType extends ListenerInstance, TSelec
|
|
|
28
41
|
connected: boolean;
|
|
29
42
|
connecting: boolean;
|
|
30
43
|
timestamp: number | null;
|
|
44
|
+
status: ListenerStatusType;
|
|
45
|
+
error: Error | null;
|
|
31
46
|
};
|
|
47
|
+
export {};
|
|
32
48
|
//# sourceMappingURL=use-listener.hooks.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-listener.hooks.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-listener/use-listener.hooks.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"use-listener.hooks.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-listener/use-listener.hooks.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,4BAA4B,EAC5B,eAAe,EACf,gBAAgB,EAEhB,uBAAuB,EACxB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAKrF,8GAA8G;AAC9G,KAAK,uBAAuB,CAAC,YAAY,SAAS,gBAAgB,IAChE,uBAAuB,CAAC,YAAY,CAAC,SAAS,IAAI,GAC9C,YAAY,GAAG;IAAE,+DAA+D,EAAE,KAAK,CAAA;CAAE,GACzF,YAAY,CAAC;AAEnB;;;GAGG;AACH,eAAO,MAAM,WAAW,GACtB,YAAY,SAAS,gBAAgB,EACrC,SAAS,GAAG,4BAA4B,CAAC,YAAY,CAAC,EAEtD,UAAU,uBAAuB,CAAC,YAAY,CAAC,EAC/C,UAAU,sBAAsB,CAAC,4BAA4B,CAAC,YAAY,CAAC,EAAE,SAAS,CAAC;;wBA6GjE,WAAW,aA1DZ;QAAE,IAAI,EAAE,4BAA4B,CAAC,YAAY,CAAC,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KAAE,KAAK,IAAI,SA0D7C;IAG/D,yGAAyG;wBACrF,WAAW,SA5Da;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,SA4DP;IAG/D,qEAAqE;sBACnD,WAAW,SA/Da,eAAe,KAAK,IAAI,SA+DP;;;;;;;;;;;;;;;;;;;;;;;;CAiD9D,CAAC"}
|