Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 47 additions & 8 deletions nodejs/sqlcommenter-nodejs/packages/sqlcommenter-drizzle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,55 @@ app.use((c, next) => {

#### Fastify

The recommended way is the first-party plugin, which wires everything correctly:

```ts
import { sqlcommenterFastify } from "@query-doctor/sqlcommenter-drizzle/fastify";

// Register it BEFORE any plugin whose hooks issue queries (e.g. auth), so the context
// is already open when those hooks run.
await app.register(sqlcommenterFastify);
await app.register(authPlugin);
```

It hooks `onRequest`, so it tags queries from the **entire request lifecycle** — including queries
issued in other plugins' `onRequest`/`preHandler` hooks — not just the route handler. Pass
`context` to add extra fields:

```ts
await app.register(sqlcommenterFastify, {
context: (request) => ({ controller: "items" }),
});
```

##### Doing it manually

If you'd rather wire it yourself with `withRequestContext`, two things are easy to get wrong:

- **Register the hook globally with [`fastify-plugin`](https://github.com/fastify/fastify-plugin).**
A plain `app.register(plugin)` encapsulates the `onRequest` hook, so it silently does **not**
apply to routes registered in the parent scope — you get no `route`/`method` tags and no error.
- **Hook `onRequest` (not the route handler), registered before any plugin whose hooks issue
queries** (e.g. an auth plugin that resolves a session in its own `onRequest`/`preHandler`).
Wrapping only the handler misses those earlier queries.

```ts
import fp from "fastify-plugin";
import { withRequestContext } from "@query-doctor/sqlcommenter-drizzle/http";

app.addHook("onRequest", (request, _, done) => {
withRequestContext(
{
route: request.routerPath,
method: request.method,
},
done
);
const sqlcommenter = fp((app, _opts, done) => {
app.addHook("onRequest", (request, _reply, next) => {
withRequestContext(
{
// `routerPath` was removed in Fastify v5; `routeOptions.url` is the matched route pattern.
route: request.routeOptions?.url ?? request.url,
method: request.method,
},
next
);
});
done();
});

await app.register(sqlcommenter); // before auth, etc.
```
Loading
Loading