Plugins
Two small plugins on one client. The logger writes a line when a request starts and when it ends. The metrics plugin counts calls, errors and durations per endpoint, like an APM agent. Send a few requests and watch both fill in.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useState, useSyncExternalStore } from "react";
import { calls, client, logger } from "./api";
import { logStore, metricsStore } from "./plugins";
type CallName = keyof typeof calls;
const callNames = Object.keys(calls) as CallName[];
const Log = () => {
const lines = useSyncExternalStore(logStore.subscribe, logStore.get);
return (
<article>
<h6>Logger plugin</h6>
{lines.length === 0 && <p className="muted">Send a request.</p>}
<ol className="log">
{lines.map((line) => (
<li key={line.id} className={line.kind}>
{line.text}
</li>
))}
</ol>
</article>
);
};
const Metrics = () => {
const metrics = useSyncExternalStore(metricsStore.subscribe, metricsStore.get);
const rows = Object.entries(metrics);
return (
<article>
<h6>Metrics plugin</h6>
<table>
<thead>
<tr>
<th>Endpoint</th>
<th>Calls</th>
<th>Error rate</th>
<th>Avg</th>
<th>Max</th>
</tr>
</thead>
<tbody>
{rows.map(([endpoint, stats]) => (
<tr key={endpoint}>
<td>
<code>{endpoint}</code>
</td>
<td>{stats.calls}</td>
<td className={stats.errors ? "error" : undefined}>{Math.round((stats.errors / stats.calls) * 100)}%</td>
<td>{Math.round(stats.totalMs / stats.calls)} ms</td>
<td>{stats.maxMs} ms</td>
</tr>
))}
</tbody>
</table>
{rows.length === 0 && <p className="muted">No requests finished yet.</p>}
</article>
);
};
export const App = () => {
const [loggerOn, setLoggerOn] = useState(true);
const toggleLogger = (on: boolean) => {
// Plugins can be added and removed at runtime. The metrics plugin keeps counting either way.
if (on) client.addPlugin(logger);
else client.removePlugin(logger);
setLoggerOn(on);
};
const sendMany = () => {
for (let index = 0; index < 8; index += 1) {
calls[callNames[index % callNames.length]]();
}
};
return (
<main className="container">
<hgroup>
<h1>Plugins</h1>
<p>Two plugins watch every request of the client: one logs it, one measures durations and error rates.</p>
</hgroup>
<div className="toolbar">
<div className="buttons">
{callNames.map((name) => (
<button key={name} type="button" className="outline" onClick={() => calls[name]()}>
{name}
</button>
))}
<button type="button" onClick={sendMany}>
Send 8 mixed
</button>
</div>
<label>
<input
type="checkbox"
role="switch"
checked={loggerOn}
onChange={(event) => toggleLogger(event.target.checked)}
/>
Logger plugin
</label>
</div>
<div className="grid-2">
<Log />
<Metrics />
</div>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/plugins hyper-fetch-react-plugins && cd hyper-fetch-react-plugins && npm install && npm run devnew Plugin({ name })with chained hooks, wrapped in a function likeloggerPlugin().onRequestStartandonRequestFinishedrun for every request of the client, successful or not.requestTimestampandresponseTimestampon the response give the duration of each call.addPluginandremovePluginturn a plugin on and off at runtime.
How it works
-
plugins.tsdefines both plugins as functions that return aPlugin. Each hook method registers one callback and returns the plugin, so the hooks chain:new Plugin({ name: "logger" }).onRequestStart(({ request }) => writeLog(`→ ${request.method} ${request.endpoint}`, "start")).onRequestFinished(({ request, response }) => { ... }); -
onRequestFinishedgets the request and the response, whatever the outcome. The duration isresponse.responseTimestamp - response.requestTimestamp. -
The metrics plugin groups by
request.requestOptions.endpoint, the template such as/posts/:postId, so every id lands in one row.request.endpointwould be/posts/26. -
api.tsadds both plugins withclient.addPlugin(). The requests themselves have no logging or metrics code. -
The Logger plugin switch calls
client.removePlugin(logger)andclient.addPlugin(logger). The metrics keep counting while the logger is off. -
The plugins write to two tiny stores, and
App.tsxreads them withuseSyncExternalStore. A real plugin would send the same data to a logging or analytics service instead.
Plugins only observe. A plugin that throws does not break the request. Calls that were deduplicated never reach the adapter, so they are not counted: GET requests are deduplicated by default, which is why two quick 500 error clicks count once.
- Logging, tracing and analytics that must cover every request without touching each one.
- Performance budgets: alert when an endpoint gets slower or fails more often.
- Debug tools that you add in development and leave out in production.
Related
A plugin is a named object with lifecycle hooks. Added to the client with addPlugin, it sees the start and the end of
every request, which is enough for logs, durations and error rates.
