Skip to content

Global interceptors

Rafat J. Al-Barouki edited this page Dec 29, 2019 · 3 revisions

Global interceptors

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.

Requests

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, we can define global interceptors like the following :

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 and only send the request after all interceptors calls the complete method of the contextWait received in the argument.

Response

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, then the success or the fail handler will be called, unless for fail handler if we instruct the request to skip it.

Sample

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.