Pascoal Eddy Bayonne
Pascoal Eddy Bayonne

Reputation: 73

Spring State Machine | Actions (Calling External API with data & pass data to another State)

I would like to use the Action<S,E> to call an external api. How can i add more data into this Action in order to invoke an external API? Another question is what if i want to send back the response (pass data to another State)

What is the best way to add more data? I'm trying to find an alternative of using context (which i know is possible but very ugly using Key-value).

Upvotes: 0

Views: 682

Answers (1)

Daniel Vilas-Boas
Daniel Vilas-Boas

Reputation: 896

Calling an external API is the same as any executing code, you can wire in your action any executable code. This includes autowiring a Service or Gateway and retrieve the data you need.

Regarding the second question, in my company we are using the extended state (context) to expose data. Before we release the state machine we get the data inside of it and serialise to a response object using object mapper.

Here is a snippet for illustration

    @Configuration
    @RequiredArgsConstructor
    public class YourAction implements Action<States, Events> {
    
      private final YourService service;
    
      @Override
      public void execute(final StateContext<States, Events> context) {

      //getting input data examples
      final Long yourIdFromHeaders = context.getMessageHeaders().get(key, Long.class);

       final Long yourIdFromContext = context.getExtendedState().get(key, Long.class);

       //calling service
       final var responseData = service.getData(yourIdFromContext);

       //storing results
       context.getExtendedState().getVariables().put("response", responseData); 
      }

Upvotes: 1

Related Questions