Skip to main content
Version: v10.5.0

Plugin

Read the API Reference »

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.

Purpose
  1. Observe every request of a client from one place, without touching the requests.
  2. React to cache and queue changes, for example to report or sync them.
  3. Package behavior you can add to any client with addPlugin.
api/plugins/logger.ts
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),
);
api/client.ts
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.

HookFires whenReceives
onMountaddPlugin adds it{ client }
onUnmountremovePlugin removes it{ client }
onRequestCreatecreateRequest creates a request{ request }
onRequestTriggerThe adapter is about to send it{ request }
onRequestStartThe adapter starts sending it{ request }
onRequestSuccessA successful response arrives{ response, request }
onRequestErrorAn error response arrives{ response, request }
onRequestFinishedEither of the two above{ response, request }
onCacheItemChangeAn entry is created or updated{ cache, cacheKey, prevData, newData }
onCacheItemDeleteAn entry is deleted{ cache, cacheKey }
onCacheItemInvalidateAn entry is invalidated{ cache, cacheKey }
onDispatcherQueueCreatedA queue is created for a new queryKey{ dispatcher, queue }
onDispatcherItemAddedA request joins a queue{ dispatcher, queue, queueItem }
onDispatcherItemDeletedA request leaves a queue{ dispatcher, queue, queueItem }
onDispatcherQueueRunningA queue is started, paused or stopped{ dispatcher, queue, status }
onDispatcherQueueDrainedA queue has no pending requests left{ dispatcher, queue }
onDispatcherQueueClearedA queue is cleared{ dispatcher, queue }
onDispatcherClearedA whole dispatcher is cleared{ dispatcher }
onAdapterFetchThe 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:

api/plugins/errors.ts
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.

Serialize a request
Restore and send it

To keep unsent requests through a reload, you do not need a plugin: give the dispatcher a lazyStorage, see persist queues.


Options​

PluginOptionsType
Name Type Description
data
PluginData
Data stored in a plugin
name
string
Name of the plugin

Methods​

Methods
Name Description
trigger(method, data)
Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events.
onUnmount(callback)
Callback that will be executed when plugin is unmounted
onRequestTrigger(callback)
Callback that will be executed when request gets triggered
onRequestSuccess(callback)
Callback that will be executed when response is successful
onRequestStart(callback)
Callback that will be executed when request starts
onRequestFinished(callback)
Callback that will be executed when response is finished
onRequestError(callback)
Callback that will be executed when response is failed
onRequestCreate(callback)
Callback that will be executed when request is created
onMount(callback)
Callback that will be executed when plugin is mounted
onDispatcherQueueRunning(callback)
Called when a dispatcher queue transitions to running, paused, or stopped
onDispatcherQueueDrained(callback)
Called when a dispatcher queue has no more pending requests
onDispatcherQueueCreated(callback)
Called when a new dispatcher queue is created
onDispatcherQueueCleared(callback)
Called when an entire dispatcher queue is cleared
onDispatcherItemDeleted(callback)
Called when an item is removed from a dispatcher queue
onDispatcherItemAdded(callback)
Called when a new item is added to a dispatcher queue
onDispatcherCleared(callback)
Called when the dispatcher storage is fully cleared
onCacheItemInvalidate(callback)
Called when a cache entry is invalidated
onCacheItemDelete(callback)
Called when a cache entry is deleted
onCacheItemChange(callback)
Called when a cache entry is created or updated
onAdapterFetch(callback)
Called when the adapter fetcher is about to execute a request
initialize(client)
Bind the plugin to a client instance. Called automatically when the plugin is added via client.addPlugin() .


Summary
  • Create a plugin with new Plugin({ name }) and chain hooks such as onRequestFinished.
  • Add it with client.addPlugin(), remove it with removePlugin().
  • 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.

Devtools plugin
Connect a client to the HyperFlow desktop app.
Managers
Request lifecycle events without a plugin.
Plugin API reference
Every hook of the Plugin class with its signature.