Capture object property value, from incoming request in spring-cloud-gateway

708 Views Asked by At

I have a spring-cloud-gateway configuration like the one below:

@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
                  .route(r -> r.path("/api/bank/account/user/**") //intercept calls to
                               .uri("http://mrq-bank-account.cloud.host/")
                               .id("bankModule"))
                  .build();
}

This route is expected to accept two types of requests going to:

/api/bank/account/user/savingsAccount

and

/api/bank/account/user/studentAccount

The first request carries a SavingsAccount object, and the second a StudentAccount object. Both of these objects have a userRef:String property which I need to extract. Is it possible to do that somehow on the cloud-gateway-configuration by adding to it?

Basically I am trying to find out how to extract a property from an object being carried by an incoming request in a spring-cloud-gateway configuration like the one above.

This is the library method, I think could be used to achieve that:

package org.springframework.cloud.gateway.route.builder;


    /**
 * This predicate is BETA and may be subject to change in a future release. A
 * predicate that checks the contents of the request body
 * @param inClass the class to parse the body to
 * @param predicate a predicate to check the contents of the body
 * @param <T> the type the body is parsed to
 * @return a {@link BooleanSpec} to be used to add logical operators
 */
public <T> BooleanSpec readBody(Class<T> inClass, Predicate<T> predicate) {
    return asyncPredicate(
            getBean(ReadBodyRoutePredicateFactory.class).applyAsync(c -> c.setPredicate(inClass, predicate)));
}

But I would want to use that to extract the value of one of the properties of the read object and then use that value to call a service that will return a hostname - the value that must ultimately be used from the uri() method

This method from org.springframework.cloud.gateway.route.builder also looks useful

    /**
 * A filter which change the URI the request will be routed to by the Gateway.
 * @param determineRequestUri a {@link Function} which takes a
 * {@link ServerWebExchange} and returns a URI to route the request to
 * @return a {@link GatewayFilterSpec} that can be used to apply additional filters
 */
public GatewayFilterSpec changeRequestUri(Function<ServerWebExchange, Optional<URI>> determineRequestUri) {
    return filter(new AbstractChangeRequestUriGatewayFilterFactory<Object>(Object.class) {
        @Override
        protected Optional<URI> determineRequestUri(ServerWebExchange exchange, Object config) {
            return determineRequestUri.apply(exchange);
        }
    }.apply(c -> {
    }));
}
0

There are 0 best solutions below