Plugin
A Plugin observes the lifecycle of a client: requests, the cache, the dispatchers and the adapter. Use plugins for logging, metrics, error reporting or devtools. The HyperFlow devtools connect through one.
- Observe every request of a client from one place, without touching the requests.
- React to cache and queue changes, for example to report or sync them.
- Package behavior you can add to any client with
addPlugin.
import { Plugin } from "@hyper-fetch/core";
// Wrap the plugin in a function to give it options
export const LoggerPlugin = ({ prefix }: { prefix: string }) =>
new Plugin({ name: "logger" })
.onRequestStart(({ request }) =>
console.log(prefix, "start", request.method, request.endpoint),
)
.onRequestFinished(({ request, response }) =>
console.log(prefix, "done", request.endpoint, response.status),
);
export const client = createClient({
url: "https://api.example.com",
}).addPlugin(LoggerPlugin({ prefix: "[api]" }));
removePlugin(plugin) takes it off again and calls its onUnmount.
Hooks
Each method registers one callback and returns the plugin for chaining. Calling the same method again replaces the callback.
| Hook | Fires when | Receives |
|---|---|---|
onMount | addPlugin adds it | { client } |
onUnmount | removePlugin removes it | { client } |
onRequestCreate | createRequest creates a request | { request } |
onRequestTrigger | The adapter is about to send it | { request } |
onRequestStart | The adapter starts sending it | { request } |
onRequestSuccess | A successful response arrives | { response, request } |
onRequestError | An error response arrives | { response, request } |
onRequestFinished | Either of the two above | { response, request } |
onCacheItemChange | An entry is created or updated | { cache, cacheKey, prevData, newData } |
onCacheItemDelete | An entry is deleted | { cache, cacheKey } |
onCacheItemInvalidate | An entry is invalidated | { cache, cacheKey } |
onDispatcherQueueCreated | A queue is created for a new queryKey | { dispatcher, queue } |
onDispatcherItemAdded | A request joins a queue | { dispatcher, queue, queueItem } |
onDispatcherItemDeleted | A request leaves a queue | { dispatcher, queue, queueItem } |
onDispatcherQueueRunning | A queue is started, paused or stopped | { dispatcher, queue, status } |
onDispatcherQueueDrained | A queue has no pending requests left | { dispatcher, queue } |
onDispatcherQueueCleared | A queue is cleared | { dispatcher, queue } |
onDispatcherCleared | A whole dispatcher is cleared | { dispatcher } |
onAdapterFetch | The adapter starts executing a request | { adapter, request, requestId } |
A plugin only observes. When a hook throws, the request, the cache and the other plugins carry on, and the error is
thrown from a timer, where window.onerror or uncaughtException handlers see it.
Report errors
A common plugin sends failed responses to an error tracker:
import { Plugin } from "@hyper-fetch/core";
export const ErrorReportingPlugin = (
report: (message: string, extra: object) => void,
) =>
new Plugin({ name: "error-reporting" }).onRequestError(
({ request, response }) => {
report(`${request.method} ${request.endpoint} failed`, {
status: response.status,
error: response.error,
});
},
);
Requests are serializable
Plugins often store requests. request.toJSON() returns plain data, and Request.fromJSON(client, json) or
client.fromJSON(json) builds the request again. Functions such as mappers and $hooks are not part of the JSON.
To keep unsent requests through a reload, you do not need a plugin: give the dispatcher a lazyStorage, see
persist queues.
Options
| Name | Type | Description |
|---|---|---|
| data | | Data stored in a plugin |
| name | | Name of the plugin |
Methods
| Name | Description |
|---|---|
| Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. |
| Callback that will be executed when plugin is unmounted |
| Callback that will be executed when request gets triggered |
| Callback that will be executed when response is successful |
| Callback that will be executed when request starts |
| Callback that will be executed when response is finished |
| Callback that will be executed when response is failed |
| Callback that will be executed when request is created |
| Callback that will be executed when plugin is mounted |
| Called when a dispatcher queue transitions to running, paused, or stopped |
| Called when a dispatcher queue has no more pending requests |
| Called when a new dispatcher queue is created |
| Called when an entire dispatcher queue is cleared |
| Called when an item is removed from a dispatcher queue |
| Called when a new item is added to a dispatcher queue |
| Called when the dispatcher storage is fully cleared |
| Called when a cache entry is invalidated |
| Called when a cache entry is deleted |
| Called when a cache entry is created or updated |
| Called when the adapter fetcher is about to execute a request |
| Bind the plugin to a client instance. Called automatically when the plugin is added via
client.addPlugin()
. |
- Create a plugin with
new Plugin({ name })and chain hooks such asonRequestFinished. - Add it with
client.addPlugin(), remove it withremovePlugin(). - Hooks observe requests, cache, dispatchers and the adapter. A throwing hook never breaks a request.
Next steps
Runnable examples: Plugins (logging and metrics) and Devtools.