Hooks and Interceptors
Relevant source files
The following files were used as context for generating this wiki page:
Hooks and Interceptors in nestjs-query provide a mechanism to inject custom logic into the lifecycle of GraphQL CRUD operations. Hooks allow developers to modify incoming data or query filters before they reach the service layer, while interceptors (specifically HookInterceptor) facilitate the execution of these hooks during request processing. This system enables cross-cutting concerns such as automatic auditing, data validation, and dynamic filtering based on the request context.
Sources: packages/query-graphql/README.md, packages/query-graphql/tests/decorators/hook.decorator.spec.ts
Hook Architecture
Hooks are defined as classes or functions that implement specific logic for different stages of an operation. The system categorizes hooks based on the operation type and whether they handle a single record or multiple records. These hooks are registered on DTOs or entities using decorators.
Hook Execution Flow
The following diagram illustrates how hooks are invoked during a GraphQL mutation request.
The HookInterceptor captures the request, identifies the relevant hook for the operation, and executes it before the resolver calls the underlying service.
Sources: packages/query-graphql/tests/decorators/hook.decorator.spec.ts, examples/hooks/e2e/tag.resolver.spec.ts
Hook Types
The library supports several hook types that target specific CRUD actions.
| Hook Decorator | Operation Target | Usage Context |
|---|---|---|
@BeforeCreateOne | createOne | Modifies a single record before creation. |
@BeforeCreateMany | createMany | Modifies an array of records before creation. |
@BeforeUpdateOne | updateOne | Modifies the update object or ID before updating one record. |
@BeforeUpdateMany | updateMany | Modifies the update object or filter before updating multiple records. |
@BeforeDeleteOne | deleteOne | Performs logic or modifies the ID before deletion. |
@BeforeDeleteMany | deleteMany | Modifies the filter before deleting multiple records. |
@BeforeQueryMany | query | Modifies the query filter or paging before execution. |
@BeforeFindOne | findOne | Modifies the ID or query parameters before finding a record. |
Sources: packages/query-graphql/tests/decorators/hook.decorator.spec.ts:10-23
Decorator Integration
Hooks are applied to classes (typically DTOs) using decorators. The system supports inheritance, where child classes inherit hooks from base classes unless overridden.
- Registration: You apply a hook by passing a hook function or a class implementing the
Hookinterface to the corresponding decorator. - Inheritance: If a base class has a
@BeforeCreateOnehook, the child class uses that hook by default. If the child class defines its own hook of the same type, it overrides the base hook. - Resolution: The
getHooksForTypeutility retrieves the registered hooks for a specific operation and class type.
Sources: packages/query-graphql/tests/decorators/hook.decorator.spec.ts:28-60
Implementation Examples
Automatic Auditing
Hooks are frequently used to populate audit fields like createdBy or updatedBy from the request context. In E2E tests, these hooks verify that metadata is correctly appended to the input before the service saves the entity.
// Example from E2E tests: Checking createdBy field populated by a hook
it('should call beforeCreateOne hook when creating a tag', () =>
request(app.getHttpServer())
.post('/graphql')
.set(USER_HEADER_NAME, USER_NAME)
.send({
query: `mutation {
createOneTag(input: { tag: { name: "Audit Tag" } }) {
id
name
createdBy
}
}`
})
.expect(200)
.then(({ body }) => {
expect(body.data.createOneTag.createdBy).toBe(USER_NAME);
}));
Sources: examples/mongoose/e2e/tag.resolver.spec.ts:327-353, examples/hooks/e2e/tag.resolver.spec.ts:250-275
Validation and Filtering
Hooks can also be used to enforce business rules. For example, a BeforeUpdateMany hook can modify a filter to ensure a user can only update their own records, or a BeforeCreateOne hook can validate that a field like name is not empty.
Sources: examples/typeorm/e2e/todo-item.resolver.spec.ts:790-820, examples/auth/e2e/todo-item.resolver.spec.ts:550-580
Interceptor Role
The HookInterceptor acts as the bridge between the GraphQL execution and the Hook system. It extracts the input arguments (like input or filter) from the GraphQL context and passes them through the registered hooks.
Hooks and Interceptors provide a declarative way to handle data transformations and side effects, keeping resolvers clean and focused on CRUD operations. By leveraging these, developers ensure consistent behavior across all endpoints for a given entity.