Hooks option allows adding custom logic before and after operations that mutate the graph.
A mutation operation is an operation that mutate the database. For example, adding a new node to the graph, remove an edge between 2 nodes or delete multiple nodes.
There are 5 types of mutations:
Create- Create node in the graph.
UpdateOne- Update a node in the graph. For example, increment its field.
Update- Update multiple nodes in the graph that match a predicate.
DeleteOne- Delete a node from the graph.
Delete- Delete all nodes that match a predicate.
Each generated node type has its own type of mutation. For example, all
User builders, share the same generated
However, all builder types implement the generic
Hooks are functions that get an
ent.Mutator and return a mutator back. They function as middleware between mutators. It's similar to the popular HTTP middleware pattern.
There are 2 types of mutation hooks - schema hooks and runtime hooks. Schema hooks are mainly used for defining custom mutation logic in the schema, and runtime hooks are used for adding things like logging, metrics, tracing, etc. Let's go over the 2 versions:
Let's start with a short example that logs all mutation operations of all types:
Global hooks are useful for adding traces, metrics, logs and more. But sometimes, users want more granularity:
Assume you want to share a hook that mutate a field between multiple types (e.g.
User). There are ~2 ways to do this:
Schema hooks are defined in the type schema and applied only on mutations that match the schema type. The motivation for defining hooks in the schema is to gather all logic regarding the node type in one place, which is the schema.
When using schema hooks, there's a chance of a cyclic import between the schema package, and the generated ent package. To avoid this scenario, ent generates an
ent/runtime package which is responsible for registering the schema-hooks at runtime.
Users MUST import the
ent/runtime in order to register the schema hooks. The package can be imported in the
main package (close to where the database driver is imported), or in the package that creates the
Hooks are called in the order they were registered to the client. Thus,
client.Use(f, g, h) executes
f(g(h(...))) on mutations.
Also note, that runtime hooks are called before schema hooks. That is, if
h were defined in the schema, and
f was registered using
client.Use(...), they will be executed as follows:
The generated hooks package provides several helpers that can help you control when a hook will be executed.
Hooks can also be registered on active transactions, and will be executed on
Tx.Rollback. For more information, read about it in the transactions page.
entc package provides an option to add a list of hooks (middlewares) to the code-generation phase. For more information, read about it in the codegen page.