Header enriching based on response from another request

96 views Asked by At

I am working with spring integration and want to add some header to message based on response from external service and finally send to outboundGateway.

My simple flow looks like:

IntegrationFlowBuilder integrationFlow = IntegrationFlows.from(inboundGateway)
.handle(outboundGateway(url, restTemplate));

To add specified header I can use enrichHeader before handle, but in inboundGateway I expect message with JSON payload and headers. I don't want to modify payload, just add some header, and value for that should be based on response status code from another service (status code 200 or 404). Finally I want to send same payload and all headers to outboundGateway.

How to resolve that problem?

When I tried to use additional handle method, then lost my origin payload and just get response

1

There are 1 answers

0
Artem Bilan On

See enrichHeaders() operator in Java DSL and its HeaderEnricher docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-transformation.html#header-enricher.

In two words: the goal of this transformer is indeed to add extra headers into a message without modifying the payload. For your service call and its result into a header you may look into this option:

/**
 * Add a single header specification where the value is obtained by invoking the
 * {@link Function} callback. If the header exists, it will <b>not</b> be overwritten
 * unless {@link #defaultOverwrite(boolean)} is true.
 * @param name the header name.
 * @param function the function.
 * @param <P> the payload type.
 * @return the header enricher spec.
 * @see FunctionExpression
 */
public <P> HeaderEnricherSpec headerFunction(String name, Function<Message<P>, ?> function) {

of that enrichHeaders() operator. The function you are going to implement can make an external call.

If you would like to make a solution based on Spring Integration approach, you can take a look into an enrich(Consumer<EnricherSpec> enricherConfigurer) instead. That one has a also similar headerFunction(), but input for the function is a reply message after sending to the requestChannel() or requestSubFlow().

See more in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-transformation.html#payload-enricher