@pixotope/query 0.9.0 → 0.11.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.
@@ -1,37 +1,77 @@
1
1
  import { useCallback, useRef, useState } from "react";
2
2
 
3
+ /**
4
+ * The async function a mutation invokes to perform its side effect.
5
+ * @typeParam TData - The type of data the mutation resolves with.
6
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
7
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
8
+ * @param params - The variables for this mutation call.
9
+ * @param meta - Optional per-call metadata, passed through unchanged from `mutate`/`mutateAsync`.
10
+ * @returns A promise that resolves with the mutation's result.
11
+ */
3
12
  export type MutationFunction<
4
13
  TData = unknown,
5
14
  TParams = unknown,
6
15
  TMetadata = unknown,
7
16
  > = (params: TParams, meta?: TMetadata) => Promise<TData>;
8
17
 
18
+ /**
19
+ * Configuration options for {@link useMutation}.
20
+ *
21
+ * @typeParam TData - The type of data `mutationFn` resolves with.
22
+ * @typeParam TError - The error type reported to `onError`/`onSettled` and exposed via `error`.
23
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
24
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
25
+ */
9
26
  export interface MutationOptions<
10
27
  TData = unknown,
11
28
  TError = unknown,
12
29
  TParams = void,
13
30
  TMetadata = unknown,
14
31
  > {
32
+ /** The async function invoked by `mutate`/`mutateAsync` to perform the mutation. */
15
33
  mutationFn: MutationFunction<TData, TParams, TMetadata>;
34
+ /** Default variables passed to `prepareParams` (as its `defaults` argument) for every call. */
16
35
  params?: TParams;
36
+ /** Called after `mutationFn` resolves successfully. */
17
37
  onSuccess?: (
18
38
  data: TData,
19
39
  variables: TParams,
20
40
  meta?: TMetadata
21
41
  ) => Promise<unknown> | unknown;
42
+ /** Called after `mutationFn` rejects, or after `compareOrThrow` reports a failed comparison. */
22
43
  onError?: (
23
44
  error: TMutationError<TError>,
24
45
  variables: TParams,
25
46
  meta?: TMetadata
26
47
  ) => Promise<unknown> | unknown;
48
+ /**
49
+ * Called after every mutation attempt settles, whether it succeeded or failed. Exactly one of
50
+ * `data`/`error` will be defined.
51
+ */
27
52
  onSettled?: (
28
53
  data: TData | undefined,
29
54
  error: TMutationError<TError> | null,
30
55
  variables: TParams,
31
56
  meta?: TMetadata
32
57
  ) => Promise<unknown> | unknown;
58
+ /**
59
+ * Function that will be called with the result of `mutationFn` before it is stored. Returning
60
+ * `true` causes the call to fail with a {@link ComparisonFailError} instead of succeeding.
61
+ */
33
62
  compareOrThrow?: (result: TData | TError) => boolean;
63
+ /**
64
+ * Maximum time, in milliseconds, to wait for `mutationFn` to resolve before the call is
65
+ * considered failed with a `timeout` error. When omitted, the call never times out.
66
+ */
34
67
  timeout?: number;
68
+ /**
69
+ * Transforms the variables passed to `mutate`/`mutateAsync` before they reach `mutationFn`.
70
+ * @param variables - The variables passed to this call.
71
+ * @param defaults - The `params` configured on the hook, if any.
72
+ * @param meta - The per-call metadata, if any.
73
+ * @returns The variables to actually pass to `mutationFn`.
74
+ */
35
75
  prepareParams?: (
36
76
  variables: TParams,
37
77
  defaults?: TParams,
@@ -39,20 +79,37 @@ export interface MutationOptions<
39
79
  ) => TParams;
40
80
  }
41
81
 
42
- type TMutationError<TError> = TError | Error | null;
82
+ /** The error type exposed via `error`/`onError`/`onSettled` on {@link MutationOptions}, {@link MutateOptions}, and {@link useMutation}'s return value. */
83
+ export type TMutationError<TError> = TError | Error | null;
43
84
 
85
+ /**
86
+ * Per-call callback overrides accepted as the second argument to `mutate` (see
87
+ * {@link useMutation}'s return value). Called in addition to the callbacks configured via
88
+ * {@link MutationOptions}.
89
+ *
90
+ * @typeParam TData - The type of data the mutation resolves with.
91
+ * @typeParam TError - The error type reported to `onError`/`onSettled`.
92
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
93
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
94
+ */
44
95
  export interface MutateOptions<
45
96
  TData = unknown,
46
97
  TError = unknown,
47
98
  TParams = void,
48
99
  TMetadata = unknown,
49
100
  > {
101
+ /** Called after `mutationFn` resolves successfully. */
50
102
  onSuccess?: (data: TData, variables: TParams, meta?: TMetadata) => void;
103
+ /** Called after `mutationFn` rejects, or after `compareOrThrow` reports a failed comparison. */
51
104
  onError?: (
52
105
  error: TMutationError<TError>,
53
106
  variables: TParams,
54
107
  meta?: TMetadata
55
108
  ) => void;
109
+ /**
110
+ * Called after every mutation attempt settles, whether it succeeded or failed. Exactly one of
111
+ * `data`/`error` will be defined.
112
+ */
56
113
  onSettled?: (
57
114
  data: TData | undefined,
58
115
  error: TMutationError<TError> | null,
@@ -61,13 +118,26 @@ export interface MutateOptions<
61
118
  ) => void;
62
119
  }
63
120
 
64
- type MutationStatus = "idle" | "loading" | "success" | "error";
121
+ /** The status of a {@link useMutation} call, as exposed via its return value's `status`. */
122
+ export type MutationStatus = "idle" | "loading" | "success" | "error";
65
123
  type RaceErrorReason = "timeout";
66
124
  type RacePromises<T> = Promise<T | RaceErrorReason>;
67
125
 
126
+ /**
127
+ * Error thrown (and stored as the mutation's `error`) when a mutation's `compareOrThrow` option
128
+ * returns `true` for a successfully resolved result, i.e. the call is treated as a failure
129
+ * despite `mutationFn` not rejecting.
130
+ *
131
+ * @typeParam TPayload - The type of the offending result, available via `payload`.
132
+ */
68
133
  export class ComparisonFailError<TPayload = unknown> extends Error {
134
+ /** The result that `compareOrThrow` rejected. */
69
135
  public readonly payload: TPayload;
70
136
 
137
+ /**
138
+ * @param message - The error message.
139
+ * @param payload - The result that `compareOrThrow` rejected, preserved on the error.
140
+ */
71
141
  constructor(message: string, payload: TPayload) {
72
142
  super(message);
73
143
  this.name = this.constructor.name;
@@ -79,6 +149,33 @@ export class ComparisonFailError<TPayload = unknown> extends Error {
79
149
  }
80
150
  }
81
151
 
152
+ /**
153
+ * React hook for triggering an async side effect (a "mutation") and tracking its status, result
154
+ * and error, without fetching automatically the way {@link useQuery} does.
155
+ *
156
+ * @typeParam TData - The type of data `mutationFn` resolves with.
157
+ * @typeParam TError - The error type surfaced via `error` and `onError`.
158
+ * @typeParam TParams - The type of the variables passed in to trigger the mutation.
159
+ * @typeParam TMetadata - The type of the optional, per-call metadata.
160
+ * @param options - See {@link MutationOptions}.
161
+ * @returns An object with:
162
+ * - `status` - the current status: `"idle"`, `"loading"`, `"success"`, or `"error"`.
163
+ * - `result` - the data from the most recently successful call, if any.
164
+ * - `error` - the error from the most recently failed call, if any.
165
+ * - `mutate` - fire-and-forget trigger; accepts per-call `variables` and, optionally,
166
+ * {@link MutateOptions} plus `meta`.
167
+ * - `mutateAsync` - same as `mutate`, but returns the promise from `mutationFn` (rejects on
168
+ * failure) so callers can `await` it.
169
+ * - `reset` - resets `status`, `result` and `error` back to their initial values.
170
+ * @example
171
+ * ```tsx
172
+ * const { mutate, status } = useMutation({
173
+ * mutationFn: (vars: { name: string }) => createUser(vars),
174
+ * });
175
+ *
176
+ * mutate({ name: "Ada" }, { onSuccess: (user) => console.log(user.id) });
177
+ * ```
178
+ */
82
179
  export const useMutation = <
83
180
  TData = unknown,
84
181
  TError = TMutationError<unknown>,
package/src/useQuery.ts CHANGED
@@ -1,5 +1,14 @@
1
1
  import { useCallback, useEffect, useRef, useState } from "react";
2
2
 
3
+ /**
4
+ * Configuration options for {@link useQuery}.
5
+ *
6
+ * @typeParam TData - The raw data type returned by `queryFn`.
7
+ * @typeParam TError - The error type reported to `onError`/`onSettled` and exposed via `error`.
8
+ * @typeParam TParams - The type of the parameters passed to `refetch`/`queryFn`.
9
+ * @typeParam TSelectData - The type of the data after `select` has been applied. Defaults to `TData`.
10
+ * @typeParam Stateless - When `true`, the hook does not keep fetched data in state (see {@link QueryOptions.stateless}).
11
+ */
3
12
  export interface QueryOptions<
4
13
  TData = unknown,
5
14
  TError = unknown,
@@ -7,33 +16,101 @@ export interface QueryOptions<
7
16
  TSelectData = TData,
8
17
  Stateless extends true | undefined = undefined,
9
18
  > {
19
+ /**
20
+ * Function that fetches the data for this query. Called automatically on mount, whenever
21
+ * `key` changes, and whenever `refetch` is invoked.
22
+ * @param params - The params passed to `refetch`, or `undefined`/`void` for an automatic fetch.
23
+ * @param queryInfo - Contextual info about the current query: `key` is the normalized query
24
+ * key currently in use, and `lastFetchedAt` is the timestamp (ms) of the last successful fetch,
25
+ * or `undefined` if the query has never succeeded.
26
+ * @returns A promise that resolves with the fetched data.
27
+ */
10
28
  queryFn: (params: TParams | undefined | void, queryInfo: {key: TQueryKey | undefined, lastFetchedAt: number | undefined}) => Promise<TData>;
29
+ /** Called after `queryFn` resolves successfully, with the raw (pre-`select`) data. */
11
30
  onSuccess?: (data: TData) => Promise<void> | void;
31
+ /** Called after `queryFn` rejects, or after `compareOrThrow` reports a failed comparison. */
12
32
  onError?: (error: TQueryError<TError>) => Promise<void> | void;
33
+ /**
34
+ * Called after every fetch attempt settles, whether it succeeded or failed. Exactly one of
35
+ * `data`/`error` will be defined.
36
+ */
13
37
  onSettled?: (
14
38
  data: TData | undefined,
15
39
  error: TQueryError<TError> | undefined
16
40
  ) => Promise<void> | void;
41
+ /**
42
+ * Maximum time, in milliseconds, to wait for `queryFn` to resolve before the query is
43
+ * considered failed with a `timeout` error. When omitted, the query never times out.
44
+ */
17
45
  timeout?: number;
46
+ /**
47
+ * Whether the query is allowed to fetch. When `false`, `queryFn` is not called on mount,
48
+ * on `key` changes, or on an interval/focus refetch.
49
+ * @default true
50
+ */
18
51
  enabled?: boolean;
52
+ /**
53
+ * Data (or a function returning data) to seed `data` with before the first fetch resolves.
54
+ */
19
55
  initialData?: TData | Functionize<TData>;
56
+ /**
57
+ * Transforms the raw fetched data into the shape consumers should receive via `data`. Applied
58
+ * on every render, not just on fetch, so it should be cheap and side-effect free.
59
+ */
20
60
  select?: (data: TData) => TSelectData;
61
+ /**
62
+ * Whether to automatically refetch when the browser window regains focus.
63
+ * @default false
64
+ */
21
65
  refetchOnWindowFocus?: boolean;
66
+ /**
67
+ * When greater than `0`, automatically refetches on this interval (in milliseconds), as long
68
+ * as at least this much time has passed since the last successful fetch.
69
+ * @default 0
70
+ */
22
71
  refetchInterval?: number;
72
+ /**
73
+ * Function that will be called with the freshly fetched data before it is stored. Returning
74
+ * `true` causes the fetch to be treated as a failure (status becomes `"error"`, `onError`/
75
+ * `onSettled` are called) instead of a success.
76
+ */
23
77
  compareOrThrow?: (data: TData) => boolean;
78
+ /**
79
+ * Whether the query is stateless. When `true`, fetched data is not stored by the hook and the
80
+ * returned object will not include a `data` field.
81
+ * @default false
82
+ */
24
83
  stateless?: Stateless;
84
+ /**
85
+ * The query key. Whenever this array's serialized value changes, the query automatically
86
+ * refetches. Pass a stable/memoized array to avoid unintended refetches.
87
+ */
25
88
  key?: TQueryKey;
26
89
  }
27
90
 
28
- type Functionize<T> = () => T;
29
- type QueryStatus = "idle" | "loading" | "success" | "error" | "timeout";
91
+ /** A value, or a function returning it. Used to type {@link QueryOptions.initialData}. */
92
+ export type Functionize<T> = () => T;
93
+ /** The status of a {@link useQuery} call, as exposed via {@link UseQueryResult}'s `status`. */
94
+ export type QueryStatus = "idle" | "loading" | "success" | "error" | "timeout";
30
95
  type RaceErrorReason = "timeout";
31
96
  type RacePromises<T> = Promise<T | RaceErrorReason>;
32
- type WithData<TData> = { data: TData | undefined };
33
- type TQueryKey = readonly any[];
34
-
35
- type TQueryError<TError> = TError | Error | null;
36
-
97
+ /** Adds the `data` field to {@link UseQueryResult} when the query is not {@link QueryOptions.stateless}. */
98
+ export type WithQueryData<TData> = { data: TData | undefined };
99
+ /** The type of {@link QueryOptions.key}: an array whose serialized value determines when the query refetches. */
100
+ export type TQueryKey = readonly any[];
101
+
102
+ /** The error type exposed via {@link UseQueryResult}'s `error` and passed to `onError`/`onSettled`. */
103
+ export type TQueryError<TError> = TError | Error | null;
104
+
105
+ /**
106
+ * The value returned by {@link useQuery}.
107
+ *
108
+ * @typeParam TData - The (post-`select`) data type exposed via `data`.
109
+ * @typeParam TError - The error type exposed via `error`.
110
+ * @typeParam TParams - The type of the parameters accepted by `refetch`.
111
+ * @typeParam TSelectData - The type of the data after `select` has been applied.
112
+ * @typeParam Stateless - When `true`, the `data` field is omitted from the result.
113
+ */
37
114
  export type UseQueryResult<
38
115
  TData = unknown,
39
116
  TError = unknown,
@@ -41,12 +118,21 @@ export type UseQueryResult<
41
118
  TSelectData = TData,
42
119
  Stateless extends true | undefined = undefined,
43
120
  > = {
121
+ /** The error from the most recent failed fetch, or `null` if the last fetch succeeded (or none has happened yet). */
44
122
  error: TQueryError<TError>;
123
+ /** The current status of the query: `"idle"`, `"loading"`, `"success"`, `"error"`, or `"timeout"`. */
45
124
  status: QueryStatus;
125
+ /**
126
+ * Manually triggers a fetch, bypassing `enabled`'s effect on automatic fetches (it still
127
+ * respects the current `enabled` value at call time).
128
+ * @param params - Params to pass to `queryFn` for this fetch.
129
+ * @returns A promise that resolves once the fetch has settled.
130
+ */
46
131
  refetch: (params: TParams | void | undefined) => Promise<void>;
132
+ /** Clears `data`, `error` and `status` back to their initial values, then triggers a refetch. */
47
133
  reset: () => void;
48
134
  // eslint-disable-next-line @typescript-eslint/no-empty-object-type
49
- } & (Stateless extends true ? {} : WithData<TSelectData>);
135
+ } & (Stateless extends true ? {} : WithQueryData<TSelectData>);
50
136
 
51
137
  function normalizeQueryKey(queryKey: TQueryKey): string {
52
138
  return JSON.stringify(queryKey);
@@ -74,6 +160,28 @@ type TInternalOptionsRef<TData> = {
74
160
 
75
161
  const getRandomUUID = () => Math.random().toString(36).substring(2, 15);
76
162
 
163
+ /**
164
+ * React hook for fetching, caching (per-render, in component state) and refetching async data.
165
+ *
166
+ * `queryFn` runs automatically on mount, whenever `key` changes, and whenever `refetch` is
167
+ * called. It races against `timeout` (when provided), and its result is exposed via `data`
168
+ * (after `select`, if provided), `status`, and `error`.
169
+ *
170
+ * @typeParam TData - The raw data type returned by `queryFn`.
171
+ * @typeParam TError - The error type surfaced via `error` and `onError`.
172
+ * @typeParam TParams - The type of the parameters accepted by `refetch`.
173
+ * @typeParam TSelected - The type of the data after `select` has been applied. Defaults to `TData`.
174
+ * @typeParam Stateless - When `true`, the hook does not keep fetched data in state.
175
+ * @param options - See {@link QueryOptions}.
176
+ * @returns See {@link UseQueryResult}.
177
+ * @example
178
+ * ```tsx
179
+ * const { data, status, error, refetch } = useQuery({
180
+ * key: ["user", userId],
181
+ * queryFn: () => fetchUser(userId),
182
+ * });
183
+ * ```
184
+ */
77
185
  export const useQuery = <
78
186
  TData = unknown,
79
187
  TError = TQueryError<unknown>,
@@ -3,6 +3,16 @@ import {
3
3
  useSubscriptionCore,
4
4
  } from "./useSubscriptionCore";
5
5
 
6
+ /**
7
+ * Configuration options for {@link useSubscription}. Extends {@link SubscriptionCoreOptions}
8
+ * (minus `subscriberFn`, which `useSubscription` builds internally) with the service/topic pair
9
+ * that identifies what to subscribe to.
10
+ *
11
+ * @typeParam TData - The data type exposed via `data`, after `select` (if provided).
12
+ * @typeParam TMessage - The raw message type received from the topic.
13
+ * @typeParam Stateless - When `true`, the hook does not keep the latest message in state.
14
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `subscriptionHandler`.
15
+ */
6
16
  export type SubscriptionOptions<
7
17
  TData,
8
18
  TMessage = unknown,
@@ -12,13 +22,28 @@ export type SubscriptionOptions<
12
22
  SubscriptionCoreOptions<TData, TMessage, Stateless>,
13
23
  "subscriberFn"
14
24
  > & {
25
+ /** The name of the service/machine that owns the topic being subscribed to. */
15
26
  service: string;
27
+ /** The name of the topic to subscribe to. */
16
28
  topic: string;
29
+ /** How many levels deep to mirror nested updates. Forwarded as-is to `subscriptionHandler`. */
17
30
  maxDownwardDepth?: number;
18
31
  } & {
32
+ /** Optional metadata forwarded to `subscriptionHandler` alongside the subscription request. */
19
33
  meta?: TMetadata;
20
34
  };
21
35
 
36
+ /**
37
+ * The shape of a low-level subscription transport function, e.g. one bound to a ZMQ proxy client
38
+ * via {@link bindClientSocketProxy}. Given subscription details, it starts the subscription and
39
+ * returns an unsubscribe function.
40
+ *
41
+ * @typeParam TMessage - The raw message type delivered to `callback`.
42
+ * @typeParam TMetadata - The type of the optional metadata passed through `opts.meta`.
43
+ * @param opts - The service/topic to subscribe to, the callback to invoke per message, and any
44
+ * transport-specific options.
45
+ * @returns A function that unsubscribes from the topic.
46
+ */
22
47
  export type TSubscriptionHandlerFunction<
23
48
  TMessage,
24
49
  TMetadata extends {} = {},
@@ -31,6 +56,28 @@ export type TSubscriptionHandlerFunction<
31
56
  } & { meta?: TMetadata }
32
57
  ) => () => void;
33
58
 
59
+ /**
60
+ * React hook that subscribes to a `service`/`topic` pair via a transport-specific
61
+ * `subscriptionHandler` (see {@link TSubscriptionHandlerFunction}), managing subscribe/unsubscribe
62
+ * across the component's lifecycle. Built on top of {@link useSubscriptionCore} — see that hook
63
+ * for the mechanics of status tracking, `select`, `compareOrThrow`, etc.
64
+ *
65
+ * @typeParam TData - The data type exposed via `data`, after `select` (if provided).
66
+ * @typeParam TMessage - The raw message type received from the topic.
67
+ * @typeParam Stateless - When `true`, the hook does not keep the latest message in state.
68
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `subscriptionHandler`.
69
+ * @param subscriptionHandler - The transport function that performs the actual subscribe/unsubscribe.
70
+ * @param options - See {@link SubscriptionOptions}.
71
+ * @returns See {@link SubscriptionCoreReturnType}: `status`, `data` and `reSubscribe`
72
+ * (`data`/`status` are omitted when `Stateless` is `true`).
73
+ * @example
74
+ * ```tsx
75
+ * const { data, status } = useSubscription(bindClientSocketProxy(proxyClient), {
76
+ * service: "MyService",
77
+ * topic: "MyTopic",
78
+ * });
79
+ * ```
80
+ */
34
81
  export function useSubscription<
35
82
  TData = unknown,
36
83
  TMessage = TData,
@@ -60,6 +107,22 @@ export function useSubscription<
60
107
  });
61
108
  }
62
109
 
110
+ /**
111
+ * Builds a `useSubscription`-like hook that is pre-bound to a specific transport
112
+ * (`subscriptionHandler`) and a way of resolving the target service/machine name, so calling code
113
+ * only needs to supply the `topic` (and, optionally, override the `machine`).
114
+ *
115
+ * This is the building block behind per-domain subscription hooks: a package can call this once
116
+ * with its own transport binder and machine-resolution logic, and export the resulting hook for
117
+ * consumers to use without having to know about services/transports at all.
118
+ *
119
+ * @typeParam TMetadata - The type of the optional metadata forwarded to `subscriptionHandler`.
120
+ * @param subscriptionHandler - The transport function that performs the actual subscribe/unsubscribe.
121
+ * @param targetMachine - Resolves the service name to subscribe on, given an optional `machine`
122
+ * override supplied by the caller of the built hook.
123
+ * @returns A `useSubscriptionBuilder` hook with the same options as {@link useSubscription} minus
124
+ * `service`, plus an optional `machine` override.
125
+ */
63
126
  export function buildServiceSubscriptionHook<TMetadata extends {} = {}>(
64
127
  subscriptionHandler: TSubscriptionHandlerFunction<unknown, TMetadata>,
65
128
  targetMachine: (machine: string | undefined) => string
@@ -1,103 +1,116 @@
1
1
  /**
2
- * @fileoverview useSubscriptionCore
3
- * @name useSubscriptionCore.ts
4
- * @description useSubscriptionCore | This hook handle core subscription logic
5
- * and provides a way to subscribe and unsubscribe to a topic via any callback
2
+ * Core subscription logic: subscribe and unsubscribe to a topic via any
3
+ * callback-based transport. See {@link useSubscriptionCore}.
6
4
  */
7
5
 
8
6
  import { shallowEqual } from "@pixotope/utils/comparison";
9
7
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
10
8
 
11
- type SubscriptionState = "idle" | "subscribed" | "subscribing" | "error";
9
+ /** The status of a {@link useSubscriptionCore} subscription, as exposed via {@link WithStatus.status}. */
10
+ export type SubscriptionState = "idle" | "subscribed" | "subscribing" | "error";
12
11
 
12
+ /** A function invoked with each message received on the subscription. */
13
13
  export type MessageHandler<TMessage> = (message: TMessage) => void;
14
+
15
+ /**
16
+ * Handle passed to a {@link SubscriptionCoreOptions.subscriberFn} implementation so it can report
17
+ * subscription lifecycle events back into the hook.
18
+ */
14
19
  export type Connection = {
20
+ /** Marks the subscription as `"subscribed"`. Call this once the subscription is confirmed active. */
15
21
  acknowledge: () => void;
16
22
  };
23
+
24
+ /**
25
+ * Configuration options for {@link useSubscriptionCore}.
26
+ *
27
+ * @typeParam TData - The data type exposed via `data`, after `select` (if provided).
28
+ * @typeParam TMessage - The raw message type passed to `subscriberFn`'s handler.
29
+ * @typeParam Stateless - When `true`, the hook does not keep the latest message in state.
30
+ */
17
31
  export type SubscriptionCoreOptions<
18
32
  TData,
19
33
  TMessage = TData,
20
34
  Stateless extends true | undefined = undefined,
21
35
  > = {
22
- /**
23
- * @description Function that will be called when the message is received.
24
- */
36
+ /** Function that will be called when the message is received. */
25
37
  onMessage?: (message: TMessage) => void;
26
- /**
27
- * @description Function that will be called when the subscription is created.
28
- */
38
+ /** Function that will be called when the subscription is created. */
29
39
  onSubscribed?: (message: TMessage) => void;
30
- /**
31
- * @description Function that will be called when the subscription is created.
32
- */
40
+ /** Function that will be called when the subscription errors. */
33
41
  onError?: (error: TMessage) => void;
34
42
  /**
35
- * @description Whether the subscription is enabled.
43
+ * Whether the subscription is enabled.
36
44
  * @default true
37
45
  */
38
46
  enabled?: boolean;
39
47
  /**
40
- * @description Function that will be called before the message is processed.
48
+ * Function that will be called before the message is processed.
41
49
  * Returning `true` will cause the message to not be set to state and call {@link onError} if provided.
42
50
  * Status will be set to `error`.
43
51
  */
44
52
  compareOrThrow?: (data: TMessage) => boolean;
45
- /**
46
- * @description Function that will be called to select the data from the message.
47
- */
53
+ /** Function that will be called to select the data from the message. */
48
54
  select?: (data: TMessage) => TData;
49
55
  /**
50
- * @description Initial state of the subscription.
56
+ * Initial state of the subscription.
51
57
  * @default undefined
52
58
  */
53
59
  initialState?: TData;
54
- /**
55
- * @description Function that will be called when the subscription is created.
56
- */
60
+ /** Function that will be called when the subscription is created. */
57
61
  subscriberFn: (
58
62
  handler: MessageHandler<TMessage>,
59
63
  connection: Connection
60
64
  ) => () => void /** unsubscribe Fn */;
61
65
  /**
62
- * @description Whether the subscription is stateless. Data will not be
66
+ * Whether the subscription is stateless. Data will not be
63
67
  * stored by the hook internally.
64
68
  * @default false
65
69
  */
66
70
  stateless?: Stateless;
67
71
  /**
68
- * @description Custom equality function for comparing data.
72
+ * Custom equality function for comparing data.
69
73
  * @default shallowEqual
70
74
  */
71
75
  isEqual?: <T = TData>(a: T, b: T) => boolean;
72
76
  };
73
77
 
74
- type WithStatus = {
78
+ /** Adds the `status` field to {@link SubscriptionCoreReturnType}. */
79
+ export type WithStatus = {
75
80
  status: SubscriptionState;
76
81
  };
77
82
 
78
- type WithData<TData> = {
83
+ /** Adds the `data` field to {@link SubscriptionCoreReturnType}. */
84
+ export type WithSubscriptionData<TData> = {
79
85
  data: TData;
80
86
  };
81
87
 
88
+ /**
89
+ * The value returned by {@link useSubscriptionCore}.
90
+ *
91
+ * @typeParam TData - The data type exposed via `data`.
92
+ * @typeParam Stateless - When `true`, `status` and `data` are omitted from the result.
93
+ */
82
94
  export type SubscriptionCoreReturnType<
83
95
  TData,
84
96
  Stateless extends true | undefined,
85
97
  > = {
98
+ /** Unsubscribes (if currently subscribed) and immediately subscribes again. */
86
99
  reSubscribe: () => void;
87
100
  // eslint-disable-next-line @typescript-eslint/no-empty-object-type
88
- } & (Stateless extends true ? {} : WithStatus & WithData<TData>);
101
+ } & (Stateless extends true ? {} : WithStatus & WithSubscriptionData<TData>);
89
102
 
90
103
  /**
91
- * @description `useSubscriptionCore` | This hook handle core subscription logic
92
- * and provides a way to subscribe and unsubscribe to a topic via any callback.
93
- * The hook expose a handler function. All the consumer code need to do is to
94
- * call this handler function with the message received from the topic or pass
95
- * it directly to the callback function that is passed to the subscriberFn.
104
+ * `useSubscriptionCore` handles core subscription logic and provides a way to
105
+ * subscribe and unsubscribe to a topic via any callback. The hook exposes a
106
+ * handler function - all the consumer code needs to do is call this handler
107
+ * function with the message received from the topic, or pass it directly to
108
+ * the callback function that is passed to `subscriberFn`.
96
109
  * - `status` - current status of the subscription
97
110
  * - `data` - the data after the select function is applied to the message
98
111
  * - `reSubscribe` - function that can be called to re-subscribe to the topic
99
112
  *
100
- * An example how this hook works can be found in {@link ./useSubscription.ts}
113
+ * See {@link useSubscription} for an example of how this hook is used.
101
114
  */
102
115
  export function useSubscriptionCore<
103
116
  TData = unknown,
package/typedoc.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "entryPoints": ["src/index.ts"]
3
+ }