Global interceptors allows us to intercept the requests/responses of domino-rest and modify the requests before they are sent to the server, or the response after it is received from the server.
In many cases we might need to intercept all rest requests to add some extra headers, like security headers or authentication tokens, and it would be painful to do this for each request one at a time. and for this domino-rest allow defining global interceptors that can intercept all requests using DominoRestConfig. Example :
public class TokenInterceptor implements RequestInterceptor {
@Override
public void interceptRequest(ServerRequest request, ContextAggregator.ContextWait<ServerRequest> contextWait) {
request.setHeader("Authorization", "some token goes here");
contextWait.complete(request);
}
}
The request interceptors are blocking which allows us to do some other rest calls or async operation before resuming the request, requests will resume only after all interceptors calls the complete method of the contextWait received in the argument.
We can use response interceptors to intercepts generic responses, like authentication or errors, and we can add as many response interceptors as we want. These hooks fire before the actual success/fail callbacks, and the fail handler can be skipped from an interceptor. Example:
DominoRestConfig.getInstance()
.addResponseInterceptor(new ResponseInterceptor() {
@Override
public void onBeforeSuccessCallback(ServerRequest serverRequest, Response response) {
// inspect or log the response before the success callback
}
@Override
public void onBeforeFailedCallback(ServerRequest serverRequest, FailedResponseBean failedResponse) {
if (failedResponse.getStatusCode() == 401) {
serverRequest.skipFailHandler(); // suppress the fail handler when we want custom handling
}
}
@Override
public void onBeforeCompleteCallback(ServerRequest serverRequest) {
// runs for both success and failure before completion
}
@Override
public void onAfterCompleteCallback(ServerRequest serverRequest) {
// runs for both success and failure after completion callbacks
}
});
Use onBeforeSuccessCallback and onBeforeFailedCallback (instead of the deprecated interceptOnSuccess/interceptOnFailed) for per-outcome hooks. Completion hooks run for both paths: onBeforeCompleteCallback and onAfterCompleteCallback.