Home > Software engineering >  detect which endpoint entered our microservice in spring boot
detect which endpoint entered our microservice in spring boot

Time:11-08

I am currently a bit stuck with a development I have in Spring Boot

Basically, I have 2 controllers with a different URL but they will enter the same service. Inside the service.

Depending on the URL the result is almost the same only that changes the value of 1 attribute, so it goes through the same service where there is a small condition that fills a value or another.

I modified the service passing a boolean but they do not accept it, I was wondering if there is some way to know when it is in the service by which endpoint I enter?

@PutMapping("/orders/{id}")
ResponseEntity<?> complete(@PathVariable int id ) {

  return OrderService.updateOrder();
}

    
@PutMapping("/orders/{id}/complete")
ResponseEntity<?> complete(@PathVariable int id) {

  return OrderService.updateOrder();
}

CodePudding user response:

From what I understood, you want to signal your service from which Endpoint a specific function is called from.

If you have only two endpoints, then add a flag (boolean).

E.g:

@PutMapping("/orders/{id}")
ResponseEntity<?> complete(@PathVariable int id ) {

  return OrderService.updateOrder(true);
}

    
@PutMapping("/orders/{id}/complete")
ResponseEntity<?> complete(@PathVariable int id) {

  return OrderService.updateOrder(false);
}

Then handle your flag in your .updateOrder() function.

Or if you have more than two endpoints, pass the class of your Controller.

e.g.

@PutMapping("/orders/{id}")
ResponseEntity<?> complete(@PathVariable int id ) {

  return OrderService.updateOrder(this.getClass());
}

    
@PutMapping("/orders/{id}/complete")
ResponseEntity<?> complete(@PathVariable int id) {

  return OrderService.updateOrder(this.getClass());
}

And then in your updateOrder(Class clazz) function, handle it this way:

if(clazz == FirstController.class)
{
    ...
}
else
if(clazz == SecondController.class)
{
    ...
}

// and so on

There are endless ways to do this though... You could use enums, integers, strings, etc...

CodePudding user response:

I'd say the cleanest solution from the point of view of maintainability, where you would have the service expose two methods like this ...

And then you use the appropriate method in your contoller

class OrderService {
   updateOrderOneWay() {updateOrder(); ... some custom logic}
   updateOrderAnotherWay() {updateOrder(); ... some custom logic}
   private updateOrder()
}
  • Related