Skip to content

Instantly share code, notes, and snippets.

@aaabramov
Created January 12, 2021 12:26
Show Gist options
  • Save aaabramov/62f5eaadb82c366c48ac2cad7219fe3e to your computer and use it in GitHub Desktop.
Save aaabramov/62f5eaadb82c366c48ac2cad7219fe3e to your computer and use it in GitHub Desktop.
akka-http validate path param with reusable directive
// https://stackoverflow.com/questions/65669069/akka-http-validate-path-segment
import akka.http.scaladsl.model.Uri.Path
import akka.http.scaladsl.server.{Directive, Rejection}
import com.exabeam.scheduler.models.AppErrors
import org.bson.types.ObjectId
final case class MalformedPathParamRejection(parameterName: String, errorMsg: String) extends Rejection
object ValidatedObjectId {
def apply(directive: Directive1[String]): Directive1[String] = {
directive.filter(ObjectId.isValid, MalformedPathParamRejection("userId", "Got invalid userId"))
}
}
val complexRoute: Route = ValidatedObjectId(path(Segment)) { userId =>
get {
complete(StatusCodes.OK, s"Got userId: $userId")
} ~
post {
complete(StatusCodes.OK)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment