0

I want to have a base route that receive a IntNumber and make some checks with the database to know if the values is correct or not and then If the value is correct I want to propagate the value to child routes.

Base Route

class BaseServiceRoute extends PathDirectives with SecurityDirectives {

  val baseUserRoute = pathPrefix("user" / IntNumber)

}

How can I make some checks for the value IntNumber and the delegate the value to the child route? Directives?

Child Route

class CategoryServiceRoute(implicit executionContext: ExecutionContext) extends BaseServiceRoute {

val route = baseUserRoute { userId =>
  pathPrefix("category") {
    pathEndOrSingleSlash {
      get {
        complete(s"$userId")
      }
    } ~
      path(LongNumber) { categoryId =>
        get {
          complete(s"$categoryId")
        } ~
          post {
            complete("Hello category post")
          }
      }
     }
    }
   }

Thanks

joselufo
  • 3,393
  • 3
  • 23
  • 37

1 Answers1

2

The best-practice suggestion would be just to nest the routes so that you can still access the value from the outer route like this:

pathPrefix("user" / IntNumber) { userId =>
  pathPrefix("category") {
    pathEndOrSingleSlash {
      get {
        complete(s"$userId")
      }
    }
  }
}

However, you seem to want to separate routes into multiple parts which is perfectly fine. In that case just make the child route a def:

def childRoute(userId: Int): Route =
  pathPrefix("category") {
    pathEndOrSingleSlash {
      get {
        complete(s"$userId")
      }
    }
  }

and then use it like this:

baseUserRoute(childRoute)
jrudolph
  • 8,307
  • 4
  • 32
  • 50