I just published my first Hex library Injecto (link to repo), which roughly means Into JSON schema and Ecto. Declaring:
defmodule Post do
@properties %{
title: {:string, required: true},
description: {:string, []},
likes: {:integer, required: true, minimum: 0}
}
use Injecto
end
defines Post
as an Ecto schema, and has an accessible JSON schema along with the options:
%ExJsonSchema.Schema.Root{
schema: %{
"properties" => %{
"description" => %{
"anyOf" => [%{"type" => "string"}, %{"type" => "null"}]
},
"likes" => %{"minimum" => 0, "type" => "integer"},
"title" => %{"type" => "string"}
},
"required" => ["likes", "title"],
"title" => "Elixir.Post",
"type" => "object",
"x-struct" => "Elixir.Post"
},
refs: %{},
definitions: %{},
location: :root,
version: 7,
custom_format_validator: nil
}
For a bit of background, I was looking for a tool to achieve a couple of things:
- validate data coming in from external sources and data going out; and
- validate requests and responses using JSON schema and expose the specs using Swagger.
For point 1, I found Ecto changesets and Elixir structs to be really nice to work with, but I couldn’t find anything to automatically translate Ecto schemas into JSON schemas (CMIIW). As for point 2, ex_json_schema
works well, but defining JSON schemas by hand is quite clunky, and I didn’t find a way to do automatic struct definition.
I set out to write my own solution for the two options above - that seems to be the recommendation out of this discussion. However, I found that the code I wrote was quite verbose, and packing it into a use
macro seems to cut down a lot of the boilerplate code.
I’m still very new with Elixir. Any comments or feedback or suggestions to do things a better way would be very much appreciated!