RESTHeart 3.0 is the latest stable version.
Request Hooks allow to execute custom code after a request completes.
For example, request hooks can be used:
- to send a confirmation email when a user registers
- to send push notifications when a resource is updated so that its properties satisfy a given condition.
Request Hooks are implemented in java and declared in the RESTHeart configuration file; once they are ready, they can be bound to resources via the
hooks collection metadata.
The class(es) that implements the Hook must be added to the java classpath.
For example, if the hook is packaged in the myhook.jar file, start RESTHeart with the following command:
$ java -server -classpath restheart.jar:myhook.jar org.restheart.Bootstrapper restheart.yml
The hooks collection metadata
With RESTHeart, not only documents but also dbs and collections have properties. Some properties are metadata, i.e. they have a special meaning for RESTheart that influences its behavior.
The collection metadata property
hooks allows to declare the hooks to be applied to the requests involving the collection and its documents.
hooks is an array of objects with the following format:
name of the hook as defined in the configuration file.
|arguments to be passed to the hook.||No|
How to develop an Hook
Hooks are developed implementing the java interface org.restheart.hal.metadata.singletons.Hook.
To add a dependency on RESTHeart using Maven, use the following:
The Hook interface requires to implement two methods:
hook(HttpServerExchange exchange, RequestContext context, BsonValue args);
doesSupportRequests() determines if the
hook() method should be executed checking the
RequestContext object that encapsulates all information about the request.
For instance, the following implementation returns
true if the request actually created a document (either POSTing the collection or PUTing the document):
Note the following useful
|getDbOperationResult()||returns the |
|getType()||returns the request resource type, e.g. DOCUMENT, COLLECTION, etc.|
|getMethod()||returns the request method, e.g. GET, PUT, POST, PATCH, DELETE, etc.|
hook() method is where the custom logic is defined.
It has three arguments:
RequestContextthat give information about the request
- the optional json
argsobject specified in the hook collection metadata.
How to declare an Hook in the configuration file
The metadata-named-singletons section of the configuration file defines, among others, the hooks group: here hook implementation classes can be bound to logical names that can be used in the hooks collection metadata.
The following is the default hooks configuration that declares the example snooper hook (that just logs resource status before and after request db operation execution).