Therapy - Crystal input parsing and validation library

Therapy is a new library for parsing and validating structured input data (think JSON or HTTP form data). It does not require any classes to be made with macros, modules, or annotations. The input structure is defined with any validations. You parse the input and you get back a result with your parsed output or any errors.

Example

require "therapy"

INPUT_FORM = Therapy.object(
  email: Therapy.string,
  role: Therapy.string.one_of("admin", "user", "guest"),
  data: Therapy.array(Therapy.int),
  opt: Therapy.string.strip.optional
)

json = JSON.parse(<<-RAW)
{
  "email": "foo@example.com",
  "role": "user",
  "data": [1, 4, 6],
  "opt": "     input  "
}
RAW

INPUT_FORM.parse!(json) #=> NamedTuple(email: "foo@example.com", role: "user", data: [1, 4, 6] of Int32, opt: "input")

If you are familiar with typescript’s Zod, this library was inspired by that.

I intend for Therapy to be the simplest parsing and validation library around so please let me know what you think!

6 Likes

Do you plan to also provide high level validations like email, URL, URI, path, or is high level not in the scope of your library?

Yes, I do. There’s a bunch of little pieces I want to add… but I’ve had this library in the works for several years (not continuously working on it, I took a couple years off) and just wanted to get it out there.