Giter VIP home page Giter VIP logo

akkurate's Introduction

Akkurate

Get started by reading the documentation

Akkurate is a validation library taking advantage of the expressive power of Kotlin. No need
for 30+ annotations or complicated custom constraints; write your validation code in Kotlin with a beautiful declarative API.

Designed from scratch to handle complex business logic, its role is to help you write qualitative and maintainable validation code.

A code example of Akkurate used to showcase the library on social networks.

Warning

Akkurate is under development and, despite being heavily tested, its API isn't yet stabilized; breaking changes might happen on minor releases. However, we will always provide migration guides.

Report any issue or bug in the GitHub repository.

Showcase

Here's an example showcasing how you can constrain a book and its list of authors.

// Define your classes

@Validate
data class Book(
    val title: String,
    val releaseDate: LocalDateTime,
    val authors: List<Author>,
)

@Validate
data class Author(val firstName: String, val lastName: String)

// Write your validation rules

val validateBook = Validator<Book> {
    // First the property, then the constraint, finally the message.
    title.isNotEmpty() otherwise { "Missing title" }

    releaseDate.isInPast() otherwise { "Release date must be in past" }

    authors.hasSizeBetween(1..10) otherwise { "Wrong author count" }

    authors.each { // Apply constraints to each author
        (firstName and lastName) {
            // Apply the same constraint to both properties
            isNotEmpty() otherwise { "Missing name" }
        }
    }
}

// Validate your data

when (val result = validateBook(someBook)) {
    is Success -> println("Success: ${result.value}")
    is Failure -> {
        val list = result.violations
            .joinToString("\n") { "${it.path}: ${it.message}" }
        println("Failures:\n$list")
    }
}

Notice how each constraint applied to a property can be read like a sentence. This code:

title.isNotEmpty() otherwise { "Missing title" }

can be read:

Check if 'title' is not empty otherwise write "Missing title".

Features

  • Beautiful DSL and API
    Write crystal clear validation code and keep it DRY. Use loops and conditions when needed; forget about annotation hell.

  • Bundled with all the essential constraints
    Write custom constraints for your business logic and nothing more. The rest? It's on us!

  • Easily and highly extendable
    No need to write verbose code to create custom constraints, within Akkurate they're as simple as a lambda with parameters.

  • Contextual and asynchronous
    Query sync/async data sources whenever you need to, like a database, or a REST API. Everything can happen inside validation.

  • Integrated with your favorite tools
    Validate your data within any popular framework, we take care of the integrations for you.

  • Code once, deploy everywhere
    Take advantage of Kotlin Multiplatform; write your validation code once, use it both for front-end and back-end usages.

  • Testable out of the box
    Finding how to test your validation code shouldn't be one of your tasks. You will find all the tools you need to write good tests.

Note

Features marked with ⏱ are on the roadmap.

akkurate's People

Contributors

nesk avatar raulraja avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

akkurate's Issues

Support validating nullable iterables

The following functions should support nullable iterables:

public operator fun <T> Validatable<Iterable<T>>.iterator(): Iterator<Validatable<T>>

public inline fun <T> Validatable<Iterable<T>>.each(block: Validatable<T>.() -> Unit)

Currently, the following code doesn't work, each isn't callable:

Validator<List<Any>?> {
    each { /* ... */ }
}

Generated accessors for mutable properties are improperly cast

@Validate
data class Book(var title: String)

should produce:

/**
 * [Validatable] accessor of [Book.title]
 */
public val Validatable<Book>.title: Validatable<String>
  @JvmName(name = "validatableBookTitle")
  get() = validatableOf(Book::title as KMutableProperty1)

/**
 * [Validatable] accessor of [Book.title]
 */
public val Validatable<Book?>.title: Validatable<String?>
  @JvmName(name = "validatableNullableBookTitle")
  get() = validatableOf(Book::title as KMutableProperty1)

instead of:

/**
 * [Validatable] accessor of [Book.title]
 */
public val Validatable<Book>.title: Validatable<String>
  @JvmName(name = "validatableBookTitle")
  get() = validatableOf(Book::title as KProperty1)
//                                     ^ cast error

/**
 * [Validatable] accessor of [Book.title]
 */
public val Validatable<Book?>.title: Validatable<String?>
  @JvmName(name = "validatableNullableBookTitle")
  get() = validatableOf(Book::title as KProperty1)
//                                     ^ cast error

Support overriding the visibility of the generated accessors

  • we sould ignore all private/protected properties
  • we should generate accessors for internal/public properties
  • a property can be public in a private class, we should be careful with this
  • the accessor should have the same visibility than the property
  • the user should be able to override the visibility of the whole accessors, to force them being internal for example, to avoid leaks into the public API

Expose a helper to test custom constraints

Describe the bug
I'm defining custom constraints and there seems to be no easy way to test them. In the following example, I'd like to create a Validatable<String>, but without the helpers defined in the _test package, it's hard to do because the ConstraintRegistry class is internal.

fun Validatable<String>.isValidTimeZone() = constrain {
    kotlin.runCatching { TimeZone.of(it) }.isSuccess
} otherwise {
    "Should be a valid time zone"
}

Expected behavior
Would it be possible to expose the helper functions, maybe in a test library so that it's possible to unit test the custom constraints?

fun "test_time_zone_constraint" {
  assertTrue(Validatable("America/New_York").isValidTimeZone().satisfied)
}

Thanks!

Kotlin Multiplatform support

Hi
Thank you for your helpful library.
I want to use this library in shared module in kotlin multiplatform project but it doesn't support kotlin multiplatform.
Can you work on it?

Add basic missing constraints

CharSequence:

  • hasLengthEqualTo, hasLengthNotEqualTo
  • isBlank, isNotBlank
  • regex with isMatching, isNotMatching

All collections:

  • isEmpty, isNotEmpty
  • hasSizeEqualTo, hasSizeNotEqualTo
  • isContaining, isNotContaining

Explore the idea of attaching custom details to ConstraintViolation

The ConstraintViolation has path and message, which is sufficient for most cases.

But it is not the most straightforward design if I need to pinpoint on the exact constraint being violated and act on it. For instance, to pick out a particular constraint violation and throw an alternate Exception instead of the generic Exception.

Currently, to workaround this limitation, there are possibly two ways:

  • Override the path using the withPath { absolute("some_identifier") } DSL
  • Override the message using the otherwise { "some_identifier" } DSL

The first workaround loses the path in a meaningful way. And the second workaround loses human readable messages.

Is it possible to add a third field of metadata: Map<String, Any> to ConstraintViolation, so that user can freely attach whatever metadata they need to the violation instance.

Possible DSL design:

val validate = Validator<Data> {
   fieldOne.apply {
      shouldNotBeEmpty()
      constraint { it.meetsCustomCondition() } withMetadata { mapOf("key" to "customErrorKey1") }
   }
}

Then, when analyzing the ConstraintViolation:

fun handleViolation(cv: ConstraintViolation) {
   if (cv.metadata["key"] == "customErrorKey1")
      throw CustomError(cv.message)
  throw FallbackError(cv.message)
}

Provide some conditional helpers

We could provide some conditional helpers :

  • ifNotNull
  • ifInstanceOf

Instead of:

if (prop.unwrap() != null) prop { // this: Validatable<SomeClass?>
    constrain { it?.someBool == true }
}

we could write:

prop.ifNotNull { // this: Validatable<SomeClass>
    constrain { it.someBool }
}

We avoid calling unwrap, the receiver is automatically defined, and it's no longer nullable.

Some helpers unrelated to type casting could be useful too:

  • ifNotEmpty (CharSequence and iterables)
  • ifNotBlank
  • ifNotNullOrEmpty
  • ifNotNullOrBlank

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.