dashbitco / nimble_options

A tiny library for validating and documenting high-level options. 💽
Apache License 2.0
507 stars 38 forks source link

Add macro to generate schemas #106

Closed dvic closed 1 year ago

dvic commented 1 year ago

Is there any interest in having a macro something along the lines of

@definition nimble_schema do
  key :connections, :non_neg_integer, default: 5
  key :url, :string, required: true
end

that generates

@definition [
  connections: [
    type: :non_neg_integer,
    default: 5
  ],
  url: [
    type: :string,
    required: true
  ]
]

If so, I'd be happy to work on this :)

dvic commented 1 year ago

For nested child keyword lists, I'd use something like

  @definition nimble_schema do
    key :url, :string, required: true
    key :foo, :keyword_list, required: true do
      field :some_key, :non_neg_integer
    end
  end

and

  @definition nimble_schema do
    key :url, :string, required: true
    key :foo, :keyword_list, required: true, keys: @existing_schema
  end
josevalim commented 1 year ago

I am :-1:. The point of NimbleOptions is to work and validate data, so it would be a bit weird and contradictory if we end-up hiding the data ourselves in favor of a DSL. :)

dvic commented 1 year ago

Now that I think of it, the only real "issue" I have with manually typing the schemas is the disjunction, e.g.,

    expected_version: [
      type:
        {:or,
         [
           {:in, [:any_version, :no_stream, :stream_exists]},
           :non_neg_integer
         ]}
    ]

Something that might be considered is to be able to write

    expected_version: [
      type: any(:any_version | :no_stream | :stream_exists, [type: :non_neg_integer])
    ]

But of course, I can write such a helper myself, just wanted to drop my reasoning for such a request here :)

josevalim commented 1 year ago

If Elixir ever has gradual typing, then this whole project needs a revamp (or perhaps even loses its use).

dvic commented 1 year ago

If Elixir ever has gradual typing, then this whole project needs a revamp (or perhaps even loses its use).

I like the sound of that ;)