Code Monkey home page Code Monkey logo

ktor-validation-feature's Introduction

Ktor validation feature

Build Status

Validation is an important part of each API. This feature provides a simple way for incoming request validation.

Let's imagine we have request object which must be validated:

data class Message(val id: Long, val message: String)

First of all, we need to implement validation logic implementing Validator interface:

object MessageValidator : Validator<Message> {

    override fun supports(clazz: KClass<*>): Boolean = Message::class == clazz

    override fun validate(obj: Message): ValidationResult {
        val errors = mutableMapOf<PropertyPath, List<ValidationError>>()
        if (obj.message.isBlank()) errors["message"] = listOf("message must be not blank")
        return ValidationResult.Invalid(errors.toMap())
    }
}

Then we need to configure the feature. There are 2 options:

  1. If object validation fails (object is not valid), then we get RequestValidationException, which we need handle. One of the options is StatusPage feature.
install(ValidationFeature) {
    validators = listOf(MessageValidator) //add MessageValidator to feature
}

//StatusPages feature is optional, otherwise you should care about exception handling by yourself
install(StatusPages) {
    exception<RequestValidationException> { cause -> 
        call.respond(HttpStatusCode.BadRequest, cause.validationResult) 
    }
}

// Some logic is here
post("/messages") {
    val message = call.receive<Message>()
    call.respond(message)
}
  1. If you don't want to throw the exception, you should set throwExceptionIfInvalid to false. In this case, you could get validation result by calling: call.receiveValidated<T>() which returns Pair<T, ValidationResult>. ValidationResult is sealed class, can be:
    • NotValidated - in case validators weren't provided
    • Valid - in case validation finished successfully
    • Invalid - in case validation failed
install(ValidationFeature) {
    validators = listOf(MessageValidator) //add MessageValidator to feature
    throwExceptionIfInvalid = false //by default, it is true
}

post("/messages") {
    val (msg, validatedResult) = call.receiveValidated<Message>()
    when (validatedResult) {
        is ValidationResult.NotValidated -> call.respond(msg.message)
        is ValidationResult.Valid -> call.respond(msg)
        is ValidationResult.Invalid -> call.respond(HttpStatusCode.BadRequest, validatedResult.errors)    
    }
}

Improvements

Add validated function for Routers

post("/") = validated {
    val (msg, validatedResult) = call.receiveValidated<Message>()
    when (validatedResult) {
        is ValidationResult.NotValidated -> call.respond(msg.message)
        is ValidationResult.Valid -> call.respond(msg)
        is ValidationResult.Invalid -> call.respond(HttpStatusCode.BadRequest, validatedResult.errors)
    }
}

ktor-validation-feature's People

Contributors

viartemev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ktor-validation-feature's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.