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. those interceptors will be called before calling the actual request success or fail handlers, except that we can skip the fail handler from the interceptor. Example :
DominoRestConfig.getInstance()
.addResponseInterceptor(new ResponseInterceptor() {
@Override
public void interceptOnSuccess(ServerRequest serverRequest, String body) {
//do something with the success response
}
@Override
public void interceptOnFailed(ServerRequest serverRequest, FailedResponseBean failedResponse) {
if(failedResponse.getStatusCode()==401){
serverRequest.skipFailHandler();
}
//do something with the failed response, maybe forward to login page.
}
});
Both methods of the ResponseInterceptor are default to do nothing.