Created
January 12, 2021 12:26
-
-
Save aaabramov/62f5eaadb82c366c48ac2cad7219fe3e to your computer and use it in GitHub Desktop.
akka-http validate path param with reusable directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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