├── test ├── test_helper.exs └── params_test.exs ├── .formatter.exs ├── lib ├── params │ ├── behaviour.ex │ ├── schema.ex │ └── def.ex └── params.ex ├── .gitignore ├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── config └── config.exs ├── mix.exs ├── mix.lock ├── CHANGELOG.md ├── README.md └── LICENSE /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /lib/params/behaviour.ex: -------------------------------------------------------------------------------- 1 | defmodule Params.Behaviour do 2 | @moduledoc false 3 | 4 | @callback from(map, Keyword.t()) :: Ecto.Changeset.t() 5 | @callback data(map, Keyword.t()) :: {:ok, struct} | {:error, Ecto.Changeset.t()} 6 | @callback changeset(Ecto.Changeset.t(), map) :: Ecto.Changeset.t() 7 | end 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | params-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: oeiuwq # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 12 | polar: # Replace with a single Polar username 13 | buy_me_a_coffee: # Replace with a single Buy Me a Coffee username 14 | thanks_dev: # Replace with a single thanks.dev username 15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 16 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | import Config 4 | 5 | # This configuration is loaded before any dependency and is restricted 6 | # to this project. If another project depends on this project, this 7 | # file won't be loaded nor affect the parent project. For this reason, 8 | # if you want to provide default values for your application for 9 | # 3rd-party users, it should be done in your "mix.exs" file. 10 | 11 | # You can configure for your application as: 12 | # 13 | # config :params, key: :value 14 | # 15 | # And access this configuration in your application as: 16 | # 17 | # Application.get_env(:params, :key) 18 | # 19 | # Or configure a 3rd-party app: 20 | # 21 | # config :logger, level: :info 22 | # 23 | 24 | # It is also possible to import configuration files, relative to this 25 | # directory. For example, you can emulate configuration per environment 26 | # by uncommenting the line below and defining dev.exs, test.exs and such. 27 | # Configuration from the imported file will override the ones defined 28 | # here (which is why it is important to import them last). 29 | # 30 | # import_config "#{Mix.env}.exs" 31 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Params.Mixfile do 2 | use Mix.Project 3 | 4 | @source_url "https://github.com/vic/params" 5 | @version "2.3.0" 6 | 7 | def project do 8 | [ 9 | app: :params, 10 | version: @version, 11 | elixir: "~> 1.2", 12 | name: "Params", 13 | deps: deps(), 14 | docs: docs(), 15 | package: package(), 16 | build_embedded: Mix.env() == :prod, 17 | start_permanent: Mix.env() == :prod, 18 | dialyzer: [plt_add_apps: [:ecto]], 19 | xref: [exclude: [Ecto.Changeset]] 20 | ] 21 | end 22 | 23 | def package do 24 | [ 25 | description: "Parameter structure validation and casting with Ecto.Schema.", 26 | files: ~w(lib mix.exs README.md LICENSE CHANGELOG.md), 27 | maintainers: ["Victor Hugo Borja "], 28 | licenses: ["Apache-2.0"], 29 | links: %{ 30 | "Changelog" => "https://hexdocs.pm/params/changelog.html", 31 | "GitHub" => @source_url 32 | } 33 | ] 34 | end 35 | 36 | def docs do 37 | [ 38 | extras: [ 39 | "CHANGELOG.md": [], 40 | LICENSE: [title: "License"], 41 | "README.md": [title: "Overview"] 42 | ], 43 | main: "readme", 44 | homepage_url: "https://hex.pm/packages/params", 45 | source_url: @source_url, 46 | formatters: ["html"] 47 | ] 48 | end 49 | 50 | def application do 51 | [extra_applications: [:logger]] 52 | end 53 | 54 | defp deps do 55 | [ 56 | {:ecto, "~> 2.0 or ~> 3.0"}, 57 | {:ex_doc, ">= 0.0.0", only: :dev, runtime: false}, 58 | {:dialyxir, "~> 0.5", only: :dev, runtime: false} 59 | ] 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | build: 6 | name: Build and test 7 | runs-on: ubuntu-20.04 8 | env: 9 | MIX_ENV: test 10 | # see https://hexdocs.pm/elixir/compatibility-and-deprecations.html#between-elixir-and-erlang-otp 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | include: 15 | - elixir: 1.18.x 16 | otp: 27.x 17 | lint: true 18 | - elixir: 1.17.x 19 | otp: 27.x 20 | - elixir: 1.17.x 21 | otp: 25.x 22 | - elixir: 1.16.x 23 | otp: 26.x 24 | - elixir: 1.16.x 25 | otp: 24.x 26 | - elixir: 1.15.x 27 | otp: 26.x 28 | - elixir: 1.15.x 29 | otp: 24.x 30 | - elixir: 1.14.x 31 | otp: 25.x 32 | - elixir: 1.14.x 33 | otp: 23.x 34 | - elixir: 1.13.x 35 | otp: 24.x 36 | - elixir: 1.13.x 37 | otp: 22.x 38 | - elixir: 1.12.x 39 | otp: 24.x 40 | - elixir: 1.12.x 41 | otp: 22.x 42 | - elixir: 1.11.x 43 | otp: 23.x 44 | - elixir: 1.11.x 45 | otp: 21.x 46 | steps: 47 | - uses: actions/checkout@v4 48 | - uses: erlef/setup-beam@v1 49 | with: 50 | elixir-version: ${{ matrix.elixir }} 51 | otp-version: ${{ matrix.otp }} 52 | - run: mix deps.get 53 | - run: mix deps.compile 54 | - run: mix compile --warnings-as-errors 55 | if: ${{ matrix.lint }} 56 | - run: mix format --check-formatted 57 | if: ${{ matrix.lint }} 58 | - run: mix deps.unlock --check-unused 59 | if: ${{ matrix.lint }} 60 | - run: mix test 61 | -------------------------------------------------------------------------------- /lib/params/schema.ex: -------------------------------------------------------------------------------- 1 | defmodule Params.Schema do 2 | @moduledoc ~S""" 3 | Defines a params schema for a module. 4 | 5 | A params schema is just a map where keys are the parameter name 6 | (ending with a `!` to mark the parameter as required) and the 7 | value is either a valid Ecto.Type, another map for embedded schemas 8 | or an array of those. 9 | 10 | ## Example 11 | 12 | defmodule ProductSearch do 13 | use Params.Schema, %{ 14 | text!: :string, 15 | near: %{ 16 | latitude!: :float, 17 | longitude!: :float 18 | }, 19 | tags: [:string] 20 | } 21 | end 22 | 23 | To get an Ecto.Changeset for ProductSearch params use: 24 | 25 | changeset = ProductSearch.from(params) 26 | 27 | To transform the changeset into a map or `%ProductSearch{}`struct use 28 | [Params.changes/1](Params.html#changes/1) or [Params.data/1](Params.html#data/1) 29 | respectively. 30 | """ 31 | 32 | @doc false 33 | defmacro __using__([]) do 34 | quote do 35 | import Params.Schema, only: [schema: 1] 36 | unquote(__use__(:ecto)) 37 | unquote(__use__(:params)) 38 | end 39 | end 40 | 41 | @doc false 42 | defmacro __using__(schema) do 43 | quote bind_quoted: [schema: schema] do 44 | import Params.Def, only: [defschema: 1] 45 | Params.Def.defschema(schema) 46 | end 47 | end 48 | 49 | @doc false 50 | defmacro schema(do: definition) do 51 | quote do 52 | Ecto.Schema.schema "params #{__MODULE__}" do 53 | unquote(definition) 54 | end 55 | end 56 | end 57 | 58 | defp __use__(:ecto) do 59 | quote do 60 | use Ecto.Schema 61 | import Ecto.Changeset 62 | @primary_key {:_id, :binary_id, autogenerate: false} 63 | end 64 | end 65 | 66 | defp __use__(:params) do 67 | quote do 68 | Module.register_attribute(__MODULE__, :required, persist: true) 69 | Module.register_attribute(__MODULE__, :optional, persist: true) 70 | Module.register_attribute(__MODULE__, :schema, persist: true) 71 | 72 | @behaviour Params.Behaviour 73 | 74 | def from(params, options \\ []) when is_list(options) do 75 | on_cast = Keyword.get(options, :with, &__MODULE__.changeset(&1, &2)) 76 | __MODULE__ |> struct |> Ecto.Changeset.change() |> on_cast.(params) 77 | end 78 | 79 | def data(params, options \\ []) when is_list(options) do 80 | case from(params, options) do 81 | ch = %{valid?: true} -> {:ok, Params.data(ch)} 82 | ch -> {:error, ch} 83 | end 84 | end 85 | 86 | def changeset(changeset, params) do 87 | Params.changeset(changeset, params) 88 | end 89 | 90 | defoverridable changeset: 2 91 | end 92 | end 93 | end 94 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "decimal": {:hex, :decimal, "2.1.1", "5611dca5d4b2c3dd497dec8f68751f1f1a54755e8ed2a966c2633cf885973ad6", [:mix], [], "hexpm", "53cfe5f497ed0e7771ae1a475575603d77425099ba5faef9394932b35020ffcc"}, 3 | "dialyxir": {:hex, :dialyxir, "0.5.1", "b331b091720fd93e878137add264bac4f644e1ddae07a70bf7062c7862c4b952", [:mix], [], "hexpm", "6c32a70ed5d452c6650916555b1f96c79af5fc4bf286997f8b15f213de786f73"}, 4 | "earmark_parser": {:hex, :earmark_parser, "1.4.39", "424642f8335b05bb9eb611aa1564c148a8ee35c9c8a8bba6e129d51a3e3c6769", [:mix], [], "hexpm", "06553a88d1f1846da9ef066b87b57c6f605552cfbe40d20bd8d59cc6bde41944"}, 5 | "ecto": {:hex, :ecto, "3.11.2", "e1d26be989db350a633667c5cda9c3d115ae779b66da567c68c80cfb26a8c9ee", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "3c38bca2c6f8d8023f2145326cc8a80100c3ffe4dcbd9842ff867f7fc6156c65"}, 6 | "ex_doc": {:hex, :ex_doc, "0.34.0", "ab95e0775db3df71d30cf8d78728dd9261c355c81382bcd4cefdc74610bef13e", [:mix], [{:earmark_parser, "~> 1.4.39", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "60734fb4c1353f270c3286df4a0d51e65a2c1d9fba66af3940847cc65a8066d7"}, 7 | "makeup": {:hex, :makeup, "1.1.2", "9ba8837913bdf757787e71c1581c21f9d2455f4dd04cfca785c70bbfff1a76a3", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "cce1566b81fbcbd21eca8ffe808f33b221f9eee2cbc7a1706fc3da9ff18e6cac"}, 8 | "makeup_elixir": {:hex, :makeup_elixir, "0.16.2", "627e84b8e8bf22e60a2579dad15067c755531fea049ae26ef1020cad58fe9578", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "41193978704763f6bbe6cc2758b84909e62984c7752b3784bd3c218bb341706b"}, 9 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.0", "6f0eff9c9c489f26b69b61440bf1b238d95badae49adac77973cbacae87e3c2e", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "ea7a9307de9d1548d2a72d299058d1fd2339e3d398560a0e46c27dab4891e4d2"}, 10 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 11 | "telemetry": {:hex, :telemetry, "1.2.1", "68fdfe8d8f05a8428483a97d7aab2f268aaff24b49e0f599faa091f1d4e7f61c", [:rebar3], [], "hexpm", "dad9ce9d8effc621708f99eac538ef1cbe05d6a874dd741de2e689c47feafed5"}, 12 | } 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/). 7 | 8 | ## [Unreleased] 9 | 10 | ## [2.3.0] - 2025-02-27 11 | 12 | ### Documentation 13 | 14 | * Miscellaneous documentation changes, including updates for HexDocs.pm. (#37 by @kianmeng) 15 | * Add example typecasting of atoms using `Ecto.Enum`. (#38 by @Ziinc) 16 | 17 | ### Fixed 18 | 19 | * Add `:logger` to `extra_applications` in `mix.exs` to fix Elixir 1.11 compiler warnings. (#35 by @greg-rychlewski) 20 | * Fix compile-time warnings in Elixir 1.14.3. (#43 by @tiagopog) 21 | * Suppress warnings in Elixir 1.17 and 1.18. (#46 by @k-asm) 22 | 23 | ## [2.2.0] - 2020-06-06 24 | 25 | ### Added 26 | 27 | * Add reusable embeds schemas with `defparams`. (#30 by @nirev) 28 | 29 | ## [2.1.1] - 2019-01-07 30 | 31 | ### Changed 32 | 33 | * Upgrade `ex_doc` to `~> 0.19`. 34 | 35 | ## [2.0.6] - 2019-01-07 36 | 37 | ### Changed 38 | 39 | * Scope modules created by `defparams` to defining module namespace. (#24 by @jgautsch) 40 | 41 | ### Fixed 42 | 43 | * Fix typo. (#26 by @accua) 44 | 45 | ### Added 46 | 47 | * Adds compatibility with Ecto 3.0. (#29 by @lasseebert) 48 | 49 | ## [2.0.5] - 2017-07-26 50 | 51 | ### Fixed 52 | 53 | * Fix Elixir 1.5 warnings. (#23 by @take-five) 54 | 55 | ## [2.0.4] - 2017-07-24 56 | 57 | ### Fixed 58 | 59 | * Fix incorrect `Params.Behaviour.data/2` typespec. (#22 by @take-five) 60 | 61 | ## [2.0.3] - 2017-07-17 62 | 63 | ### Fixed 64 | 65 | * Make defaults work with plain `use Params.Schema` in `to_map` function. (#17 by @astery) 66 | * Fixed Elixir 1.4 warnings. (#18 by @astery) 67 | * Fix Dialyzer warnings for Elixir 1.4/OTP 20. (#21 by @take-five) 68 | 69 | ## [2.0.2] - 2016-12-18 70 | 71 | ### Added 72 | 73 | * This changelog. 74 | 75 | ### Changed 76 | 77 | * Relaxed ecto dependency to 2.0 and elixir >=1.3 (#16 by @lasseebert) 78 | 79 | ## [2.0.1] - 2016-07-11 80 | 81 | ### Added 82 | 83 | * Support for ecto 2.0 84 | 85 | ### Changed 86 | 87 | * to_map now only returns the submitted keys and keys with default values. (#10 by @lasseebert) 88 | 89 | [Unreleased]: https://github.com/vic/params/compare/v2.3.0...HEAD 90 | [2.3.0]: https://github.com/vic/params/compare/v2.1.1...v2.3.0 91 | [2.2.0]: https://github.com/vic/params/compare/v2.1.1...v2.2.0 92 | [2.1.1]: https://github.com/vic/params/compare/v2.0.6...v2.1.1 93 | [2.0.6]: https://github.com/vic/params/compare/v2.0.5...v2.0.6 94 | [2.0.5]: https://github.com/vic/params/compare/v2.0.4...v2.0.5 95 | [2.0.4]: https://github.com/vic/params/compare/v2.0.3...v2.0.4 96 | [2.0.3]: https://github.com/vic/params/compare/v2.0.2...v2.0.3 97 | [2.0.2]: https://github.com/vic/params/compare/v2.0.1...v2.0.2 98 | [2.0.1]: https://github.com/vic/params/compare/c9fea01594...v2.0.1 99 | [issues]: https://github.com/vic/issues 100 | -------------------------------------------------------------------------------- /lib/params/def.ex: -------------------------------------------------------------------------------- 1 | defmodule Params.Def do 2 | @moduledoc false 3 | 4 | @doc false 5 | defmacro defparams({name, _, [schema]}, do: block) do 6 | block = Macro.escape(block) 7 | 8 | quote bind_quoted: [name: name, schema: schema, block: block] do 9 | module_name = Params.Def.module_concat(Params, __MODULE__, name) 10 | 11 | defmodule module_name do 12 | Params.Def.defschema(schema) 13 | Code.eval_quoted(block, [], __ENV__) 14 | end 15 | 16 | Code.eval_quoted( 17 | quote do 18 | def unquote(name)(params, options \\ []) do 19 | unquote(module_name).from(params, options) 20 | end 21 | end, 22 | [], 23 | module: __MODULE__ 24 | ) 25 | end 26 | end 27 | 28 | @doc false 29 | defmacro defparams({name, _, [schema]}) do 30 | quote bind_quoted: [name: name, schema: schema] do 31 | module_name = Params.Def.module_concat(Params, __MODULE__, name) 32 | 33 | defmodule module_name do 34 | Params.Def.defschema(schema) 35 | end 36 | 37 | Code.eval_quoted( 38 | quote do 39 | def unquote(name)(params) do 40 | unquote(module_name).from(params) 41 | end 42 | end, 43 | [], 44 | module: __MODULE__ 45 | ) 46 | end 47 | end 48 | 49 | @doc false 50 | defmacro defschema(schema) do 51 | quote bind_quoted: [schema: schema] do 52 | normalized_schema = Params.Def.normalize_schema(schema, __MODULE__) 53 | Code.eval_quoted(Params.Def.gen_root_schema(normalized_schema), [], module: __MODULE__) 54 | 55 | normalized_schema 56 | |> Params.Def.build_nested_schemas() 57 | |> Enum.each(fn 58 | {name, content} -> 59 | Module.create(name, content, Macro.Env.location(__ENV__)) 60 | end) 61 | end 62 | end 63 | 64 | def build_nested_schemas(schemas, acc \\ []) 65 | def build_nested_schemas([], acc), do: acc 66 | 67 | def build_nested_schemas([schema | rest], acc) do 68 | embedded = Keyword.has_key?(schema, :embeds) 69 | 70 | acc = 71 | if embedded do 72 | sub_schema = Keyword.get(schema, :embeds) 73 | 74 | module_def = { 75 | sub_schema |> List.first() |> Keyword.get(:module), 76 | Params.Def.gen_root_schema(sub_schema) 77 | } 78 | 79 | new_acc = [module_def | acc] 80 | build_nested_schemas(sub_schema, new_acc) 81 | else 82 | acc 83 | end 84 | 85 | build_nested_schemas(rest, acc) 86 | end 87 | 88 | def module_concat(parent, scope, name) do 89 | Module.concat([parent, scope, Macro.camelize("#{name}")]) 90 | end 91 | 92 | def module_concat(parent, name) do 93 | Module.concat([parent, Macro.camelize("#{name}")]) 94 | end 95 | 96 | def gen_root_schema(schema) do 97 | quote do 98 | use Params.Schema 99 | 100 | @schema unquote(schema) 101 | @required unquote(field_names(schema, &is_required?/1)) 102 | @optional unquote(field_names(schema, &is_optional?/1)) 103 | 104 | schema do 105 | (unquote_splicing(schema_fields(schema))) 106 | end 107 | end 108 | end 109 | 110 | defp is_required?(field_schema) do 111 | Keyword.get(field_schema, :required, false) 112 | end 113 | 114 | defp is_optional?(field_schema) do 115 | !is_required?(field_schema) 116 | end 117 | 118 | defp field_names(schema, filter) do 119 | for field <- schema, 120 | apply(filter, [field]), 121 | do: Keyword.get(field, :name) 122 | end 123 | 124 | defp schema_fields(schema) do 125 | Enum.map(schema, &schema_field/1) 126 | end 127 | 128 | defp schema_field(meta) do 129 | {call, name, type, opts} = { 130 | field_call(meta), 131 | Keyword.get(meta, :name), 132 | field_type(meta), 133 | field_options(meta) 134 | } 135 | 136 | quote do 137 | unquote(call)(unquote(name), unquote(type), unquote(opts)) 138 | end 139 | end 140 | 141 | defp field_call(meta) do 142 | cond do 143 | Keyword.get(meta, :field) -> 144 | :field 145 | 146 | Keyword.get(meta, :embeds_one) -> 147 | :embeds_one 148 | 149 | Keyword.get(meta, :embeds_many) -> 150 | :embeds_many 151 | 152 | Keyword.get(meta, :embeds) -> 153 | "embeds_#{Keyword.get(meta, :cardinality, :one)}" |> String.to_atom() 154 | end 155 | end 156 | 157 | defp field_type(meta) do 158 | module = Keyword.get(meta, :module) 159 | name = Keyword.get(meta, :name) 160 | 161 | cond do 162 | Keyword.get(meta, :field) -> Keyword.get(meta, :field) 163 | Keyword.get(meta, :embeds) -> module_concat(module, name) 164 | Keyword.get(meta, :embeds_one) -> Keyword.get(meta, :embeds_one) 165 | Keyword.get(meta, :embeds_many) -> Keyword.get(meta, :embeds_many) 166 | end 167 | end 168 | 169 | defp field_options(meta) do 170 | Keyword.drop(meta, [ 171 | :module, 172 | :name, 173 | :field, 174 | :embeds, 175 | :embeds_one, 176 | :embeds_many, 177 | :required, 178 | :cardinality 179 | ]) 180 | end 181 | 182 | def normalize_schema(dict, module) do 183 | Enum.reduce(dict, [], fn {k, v}, list -> 184 | [normalize_field({module, k, v}) | list] 185 | end) 186 | end 187 | 188 | defp normalize_field({module, k, v}) do 189 | required = String.ends_with?("#{k}", "!") 190 | name = String.replace_trailing("#{k}", "!", "") |> String.to_atom() 191 | normalize_field(v, name: name, required: required, module: module) 192 | end 193 | 194 | defp normalize_field({:embeds_one, embed_module}, options) do 195 | [embeds_one: embed_module] ++ options 196 | end 197 | 198 | defp normalize_field({:embeds_many, embed_module}, options) do 199 | [embeds_many: embed_module] ++ options 200 | end 201 | 202 | defp normalize_field(schema = %{}, options) do 203 | module = module_concat(Keyword.get(options, :module), Keyword.get(options, :name)) 204 | [embeds: normalize_schema(schema, module)] ++ options 205 | end 206 | 207 | defp normalize_field(value, options) when is_atom(value) do 208 | [field: value] ++ options 209 | end 210 | 211 | defp normalize_field({:array, x}, options) do 212 | normalize_field([x], options) 213 | end 214 | 215 | defp normalize_field([x], options) when is_map(x) do 216 | [cardinality: :many] ++ normalize_field(x, options) 217 | end 218 | 219 | defp normalize_field([{:field, x} | kw], options) do 220 | normalize_field(x, options) ++ kw 221 | end 222 | 223 | defp normalize_field([value], options) do 224 | [field: {:array, value}] ++ options 225 | end 226 | end 227 | -------------------------------------------------------------------------------- /lib/params.ex: -------------------------------------------------------------------------------- 1 | defmodule Params do 2 | @moduledoc ~S""" 3 | Functions for processing params and transforming their changesets. 4 | 5 | `use Params` provides a `defparams` macro, allowing you to define 6 | functions that process parameters according to some [schema](Params.Schema.html). 7 | 8 | ## Example 9 | 10 | defmodule MyApp.SessionController do 11 | use Params 12 | 13 | defparams login_params(%{email!: :string, :password!: :string}) 14 | 15 | def create(conn, params) do 16 | case login_params(params) do 17 | %Ecto.Changeset{valid?: true} = ch -> 18 | login = Params.data(ch) 19 | User.authenticate(login.email, login.password) 20 | # ... 21 | _ -> text(conn, "Invalid parameters") 22 | end 23 | end 24 | end 25 | 26 | """ 27 | 28 | @relations [:embed, :assoc] 29 | alias Ecto.Changeset 30 | 31 | @doc false 32 | defmacro __using__([]) do 33 | quote do 34 | import Params.Def, only: [defparams: 1, defparams: 2, defschema: 1] 35 | end 36 | end 37 | 38 | @doc """ 39 | Transforms an Ecto.Changeset into a Map with atom keys. 40 | 41 | Recursively traverses and transforms embedded changesets and skips keys that 42 | was not part of params given to changeset 43 | """ 44 | @spec to_map(Changeset.t()) :: map 45 | def to_map(%Changeset{data: %{__struct__: module}} = ch) do 46 | ecto_defaults = module |> plain_defaults_defined_by_ecto_schema 47 | params_defaults = module |> schema |> defaults 48 | change = changes(ch) 49 | 50 | ecto_defaults 51 | |> deep_merge(params_defaults) 52 | |> deep_merge(change) 53 | end 54 | 55 | @doc """ 56 | Transforms an Ecto.Changeset into a struct. 57 | 58 | Recursively traverses and transforms embedded changesets. 59 | 60 | For example if the `LoginParams` module was defined like: 61 | 62 | ```elixir 63 | defmodule LoginParams do 64 | use Params.Schema, %{login!: :string, password!: :string} 65 | end 66 | ``` 67 | 68 | You can transform the changeset returned by `from` into an struct like: 69 | 70 | ```elixir 71 | data = LoginParams.from(%{"login" => "foo"}) |> Params.data 72 | data.login # => "foo" 73 | ``` 74 | """ 75 | @spec data(Changeset.t()) :: struct 76 | def data(%Changeset{data: data = %{__struct__: module}} = ch) do 77 | default_embeds = default_embeds_from_schema(module) 78 | 79 | default = 80 | Enum.reduce(default_embeds, data, fn {k, v}, m -> 81 | Map.put(m, k, Map.get(m, k) || v) 82 | end) 83 | 84 | Enum.reduce(ch.changes, default, fn {k, v}, m -> 85 | case v do 86 | %Changeset{} -> Map.put(m, k, data(v)) 87 | x = [%Changeset{} | _] -> Map.put(m, k, Enum.map(x, &data/1)) 88 | _ -> Map.put(m, k, v) 89 | end 90 | end) 91 | end 92 | 93 | @doc false 94 | def default_embeds_from_schema(module) when is_atom(module) do 95 | is_embed_default = fn kw -> 96 | Keyword.get(kw, :embeds, []) 97 | |> Enum.any?(&Keyword.has_key?(&1, :default)) 98 | end 99 | 100 | default_embed = fn kw -> 101 | name = Keyword.get(kw, :name) 102 | embed_name = Params.Def.module_concat(module, name) 103 | {name, default_embeds_from_schema(embed_name)} 104 | end 105 | 106 | case schema(module) do 107 | nil -> 108 | %{} 109 | 110 | schema -> 111 | schema 112 | |> Stream.filter(is_embed_default) 113 | |> Stream.map(default_embed) 114 | |> Enum.into(struct(module) |> Map.from_struct()) 115 | end 116 | end 117 | 118 | @doc false 119 | def schema(module) when is_atom(module) do 120 | module.__info__(:attributes) |> Keyword.get(:schema) 121 | end 122 | 123 | @doc false 124 | def required(module) when is_atom(module) do 125 | module.__info__(:attributes) |> Keyword.get(:required, []) 126 | end 127 | 128 | @doc false 129 | def optional(module) when is_atom(module) do 130 | module.__info__(:attributes) 131 | |> Keyword.get(:optional) 132 | |> case do 133 | nil -> module.__changeset__() |> Map.keys() 134 | x -> x 135 | end 136 | end 137 | 138 | @doc false 139 | def changeset(%Changeset{data: %{__struct__: module}} = changeset, params) do 140 | {required, required_relations} = 141 | relation_partition(module, required(module)) 142 | 143 | {optional, optional_relations} = 144 | relation_partition(module, optional(module)) 145 | 146 | changeset 147 | |> Changeset.cast(params, required ++ optional) 148 | |> Changeset.validate_required(required) 149 | |> cast_relations(required_relations, required: true) 150 | |> cast_relations(optional_relations, []) 151 | end 152 | 153 | @doc false 154 | def changeset(model = %{__struct__: _}, params) do 155 | changeset(model |> change, params) 156 | end 157 | 158 | @doc false 159 | def changeset(module, params) when is_atom(module) do 160 | changeset(module |> change, params) 161 | end 162 | 163 | defp change(%{__struct__: _} = model) do 164 | model |> Changeset.change() 165 | end 166 | 167 | defp change(module) when is_atom(module) do 168 | module |> struct |> Changeset.change() 169 | end 170 | 171 | defp relation_partition(module, names) do 172 | types = module.__changeset__() 173 | 174 | names 175 | |> Stream.map(fn x -> String.to_atom("#{x}") end) 176 | |> Enum.reduce({[], []}, fn name, {fields, relations} -> 177 | case Map.get(types, name) do 178 | {type, _} when type in @relations -> 179 | {fields, [{name, type} | relations]} 180 | 181 | _ -> 182 | {[name | fields], relations} 183 | end 184 | end) 185 | end 186 | 187 | defp cast_relations(changeset, relations, opts) do 188 | Enum.reduce(relations, changeset, fn 189 | {name, :assoc}, ch -> Changeset.cast_assoc(ch, name, opts) 190 | {name, :embed}, ch -> Changeset.cast_embed(ch, name, opts) 191 | end) 192 | end 193 | 194 | defp deep_merge(%{} = map_1, %{} = map_2) do 195 | Map.merge(map_1, map_2, &deep_merge_conflict/3) 196 | end 197 | 198 | defp deep_merge_conflict(_k, %{} = m1, %{} = m2) do 199 | deep_merge(m1, m2) 200 | end 201 | 202 | defp deep_merge_conflict(_k, _v1, v2), do: v2 203 | 204 | defp defaults(params), do: defaults(params, %{}, []) 205 | defp defaults(params, acc, path) 206 | defp defaults([], acc, _path), do: acc 207 | defp defaults(nil, _acc, _path), do: %{} 208 | 209 | defp defaults([opts | rest], acc, path) when is_list(opts) do 210 | defaults([Enum.into(opts, %{}) | rest], acc, path) 211 | end 212 | 213 | defp defaults([%{name: name, embeds: embeds} | rest], acc, path) do 214 | acc = defaults(embeds, acc, [name | path]) 215 | defaults(rest, acc, path) 216 | end 217 | 218 | defp defaults([%{name: name, default: value} | rest], acc, path) do 219 | funs = 220 | [name | path] 221 | |> Enum.reverse() 222 | |> Enum.map(fn nested_name -> 223 | fn :get_and_update, data, next -> 224 | with {nil, inner_data} <- next.(data[nested_name] || %{}), 225 | data = Map.put(data, nested_name, inner_data), 226 | do: {nil, data} 227 | end 228 | end) 229 | 230 | acc = put_in(acc, funs, value) 231 | defaults(rest, acc, path) 232 | end 233 | 234 | defp defaults([%{} | rest], acc, path) do 235 | defaults(rest, acc, path) 236 | end 237 | 238 | defp changes(%Changeset{} = ch) do 239 | Enum.reduce(ch.changes, %{}, fn {k, v}, m -> 240 | case v do 241 | %Changeset{} -> Map.put(m, k, changes(v)) 242 | x = [%Changeset{} | _] -> Map.put(m, k, Enum.map(x, &changes/1)) 243 | _ -> Map.put(m, k, v) 244 | end 245 | end) 246 | end 247 | 248 | defp plain_defaults_defined_by_ecto_schema(module) do 249 | module 250 | |> struct 251 | |> Map.from_struct() 252 | |> Map.delete(:__meta__) 253 | |> Enum.reject(fn {_, v} -> is_nil(v) end) 254 | |> Enum.into(%{}) 255 | end 256 | end 257 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Params 2 | 3 | [Looking for maintainer](https://github.com/vic/params/issues/new?title=Becoming%20a%20maintainer) 4 | 5 | [![Hex Version](https://img.shields.io/hexpm/v/params.svg)](https://hex.pm/packages/params) 6 | [![Hex Docs](https://img.shields.io/badge/hex-docs-lightgreen.svg)](https://hexdocs.pm/params/) 7 | [![Total Download](https://img.shields.io/hexpm/dt/params.svg)](https://hex.pm/packages/params) 8 | [![License](https://img.shields.io/hexpm/l/params.svg)](https://github.com/vic/params/blob/master/LICENSE) 9 | [![Last Updated](https://img.shields.io/github/last-commit/vic/params.svg)](https://github.com/vic/params/commits/master) 10 | 11 | Easily define parameter structure and validate/cast with [Ecto.Schema][Ecto.Schema] 12 | 13 | - [About](#about) 14 | - [Installation](#installation) 15 | - [Usage](#usage) 16 | - [API Documentation](https://hexdocs.pm/params/) 17 | 18 | ## Installation 19 | 20 | [Available in Hex](https://hex.pm/packages/params), the package can be installed as: 21 | 22 | Add params to your list of dependencies in `mix.exs`: 23 | 24 | ```elixir 25 | def deps do 26 | [ 27 | {:params, "~> 2.0"} 28 | ] 29 | end 30 | ``` 31 | 32 | ## About 33 | 34 | If you've been doing [Ecto][Ecto] based applications lately, 35 | you know Ecto provides a very easy way to populate structs with data coming 36 | from request parameters, validating and casting their values along the way. 37 | 38 | All this thanks to the [Ecto.Schema][Ecto.Schema] and [Ecto.Changeset][cast] modules. 39 | The first specifies the fields your model has (typically the same as your db table) 40 | and the later provides an easy way to convert potentially unsafe data and validate 41 | stuff via changesets. 42 | 43 | So for example, in a typical [Phoenix][Phoenix] application, a `User` model 44 | would look like: 45 | 46 | ```elixir 47 | defmodule MyApp.User do 48 | use MyApp.Web, :model 49 | 50 | schema "users" do 51 | field :name, :string 52 | field :age, :integer 53 | end 54 | 55 | @required [:name] 56 | @optional [:age] 57 | 58 | def changeset(changeset_or_model, params) do 59 | cast(changeset_or_model, params, @required ++ @optional) 60 | |> validate_required(@required) 61 | end 62 | end 63 | ``` 64 | 65 | Normally, changesets are related to some data that will be persisted into 66 | a database, and your controller would use the `User.changeset` method like: 67 | 68 | ```elixir 69 | # UserController.ex 70 | def create(conn, params) do 71 | ch = User.changeset(%User{}, params) 72 | if ch.valid? do 73 | ... 74 | end 75 | ``` 76 | 77 | However, you can use `Ecto.Schema` for validating/casting data that 78 | *won't necessarily* be persisted into a database. All you need is just specify a module and 79 | define your schema, [Ecto.Changeset][cast] will be happy to work with it. 80 | 81 | This comes handy when you have certain parameter structure you want 82 | to enforce for example when creating a REST API. 83 | 84 | Some Rails developers might be right now wondering where their 85 | _strong parameters_ can be defined. On Elixir land, there's no need for such a thing, as we will see, just using an `Ecto.Schema` with `Ecto.Changeset` 86 | can be much more flexible. Using schemas allows not only 87 | specifying which fields we want, but changesets let use 88 | type cast, perform validations on values, etc. 89 | 90 | So, for example, suppose your Phoenix based API performs a search for kittens looking for a 91 | home and expects something like: 92 | 93 | ```json 94 | { 95 | "breed": "Russian Blue", 96 | "age_min": 0, 97 | "age_max": 5, 98 | "near_location": { 99 | "latitude": 92.1, 100 | "longitude": -82.1 101 | } 102 | } 103 | ``` 104 | 105 | You'd like to validate that your controller has received the correct 106 | params structure, all you need to do is create a couple of modules: 107 | 108 | ```elixir 109 | defmodule MyApi.Params.Location 110 | use Ecto.Schema 111 | import Ecto.Changeset 112 | 113 | @required ~w(latitude longitude) 114 | @optional ~w() 115 | 116 | schema "location params" do 117 | field :latitude, :float 118 | field :longitude, :float 119 | end 120 | 121 | def changeset(ch, params) do 122 | cast(ch, params, @required ++ @optional) 123 | |> validate_required(@required) 124 | end 125 | end 126 | 127 | defmodule MyAPI.Params.KittenSearch 128 | use Ecto.Schema 129 | import Ecto.Changeset 130 | 131 | @required ~w(breed) 132 | @optional ~w(age_min age_max) 133 | 134 | schema "params for kitten search" do 135 | field :breed, :string 136 | field :age_min, :integer 137 | field :age_max, :integer 138 | field :age_max, :integer 139 | field :color, Ecto.Enum, values: [:brown, :black, :grey, :unknown], 140 | embeds_one :near_location, Location 141 | end 142 | 143 | def changeset(ch, params) do 144 | cast(ch, params, @required ++ @optional) 145 | |> validate_required(@required) 146 | |> cast_embed(:near_location, required: true) 147 | end 148 | end 149 | 150 | # On your controller: 151 | def search(conn, params) do 152 | alias MyAPI.Params.KittenSearch 153 | changeset = KittenSearch.changeset(%KittenSearch{}, params) 154 | if changeset.valid? do 155 | ... 156 | end 157 | ``` 158 | 159 | That would allow you to take only valid params as you'd 160 | normally have with any other Ecto.Schema module. 161 | 162 | However it's still a lot of code, most of it 163 | defining the the changeset, specifying the optional 164 | and required fields, etc. 165 | 166 | [Params](#usage) is just a simple [Ecto.Schema][Ecto.Schema] 167 | wrapper for reducing all this boilerplate, while still 168 | leting you create custom changesets for parameter processing. 169 | 170 | ## Usage 171 | 172 | The previous example could be written like: 173 | 174 | ```elixir 175 | defmodule MyAPI.KittenController do 176 | 177 | use Params 178 | 179 | defparams kitten_search %{ 180 | breed!: :string, 181 | age_max: :integer, 182 | age_min: [field: :integer, default: 1], 183 | color: [field: Ecto.Enum, values: [:brown, :black, :grey, :unknown]], 184 | near_location!: %{ 185 | latitude!: :float, longitude!: :float 186 | }, 187 | tags: [:string] 188 | } 189 | 190 | def index(conn, params) do 191 | changeset = kitten_search(params) 192 | if changeset.valid? do 193 | search = Params.data changeset 194 | IO.puts search.near_location.latitude 195 | ... 196 | end 197 | end 198 | ``` 199 | 200 | The `defparams` macro generates a module for processing 201 | a [params schema](http://hexdocs.pm/params/Params.Schema.html) 202 | 203 | By default all fields are optional. You can mark 204 | required fields by ending them with a `!`, of course 205 | the bang is removed from the field definition and is 206 | only used to mark which fields are required by default. 207 | 208 | You can also create a module and define 209 | your schema or custom changesets in it: 210 | 211 | ```elixir 212 | defmodule UserSearch do 213 | use Params.Schema, %{name: :string, age: :integer} 214 | import Ecto.Changeset, only: [cast: 3, validate_inclusion: 3] 215 | 216 | def child(ch, params) do 217 | cast(ch, params, ~w(name age)) 218 | |> validate_inclusion(:age, 1..6) 219 | end 220 | end 221 | 222 | defmodule MyApp.UserController do 223 | 224 | def index(conn, params) do 225 | changeset = UserSearch.from(params, with: &UserSearch.child/2) 226 | if changeset.valid? do 227 | # age in 1..6 228 | end 229 | 230 | end 231 | ``` 232 | 233 | The [Params.data](http://hexdocs.pm/params/Params.html#data/1) 234 | and [Params.to_map](http://hexdocs.pm/params/Params.html#to_map/1) can be useful 235 | for obtaining a struct or map from a changeset. 236 | 237 | Note that `Params.data` and `Params.to_map` have different behaviour: `data` 238 | returns a struct which will include all valid params. `to_map` returns a map 239 | that only includes the submitted keys and keys with default values: 240 | 241 | ```elixir 242 | defmodule UserUpdateParams do 243 | use Params.Schema, %{ 244 | name: :string, 245 | age: :integer, 246 | auditlog: [field: :boolean, default: true] 247 | } 248 | end 249 | 250 | changeset = UserUpdateParams.from(%{name: "John"}) 251 | 252 | Params.data(changeset) # => %UserUpdateParams{name: "John", age: nil, auditlog: true} 253 | Params.to_map(changeset) # => %{name: "John", auditlog: true} 254 | ``` 255 | 256 | ## API Documentation 257 | 258 | [API Documentation](https://hexdocs.pm/params/) 259 | 260 | 261 | [Phoenix]: http://www.phoenixframework.org 262 | [Ecto]: https://hexdocs.pm/ecto 263 | [Ecto.Schema]: https://hexdocs.pm/ecto/Ecto.Schema.html 264 | [cast]: https://hexdocs.pm/ecto/Ecto.Changeset.html#cast/3 265 | 266 | 267 | ## Contributors 268 | 269 | Here's a list of [awesome people](https://github.com/vic/params/graphs/contributors) who have contributed code to this project. 270 | 271 | If you find a bug or want to improve something, please send a pull-request. Thank you! 272 | 273 | ## Copyright and License 274 | 275 | Copyright (c) 2016 Victor Hugo Borja 276 | 277 | Licensed under the Apache License, Version 2.0 (the "License"); 278 | you may not use this file except in compliance with the License. 279 | You may obtain a copy of the License at [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) 280 | 281 | Unless required by applicable law or agreed to in writing, software 282 | distributed under the License is distributed on an "AS IS" BASIS, 283 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 284 | See the License for the specific language governing permissions and 285 | limitations under the License. 286 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /test/params_test.exs: -------------------------------------------------------------------------------- 1 | defmodule ParamsTest do 2 | use ExUnit.Case 3 | use Params 4 | 5 | alias Ecto.Changeset 6 | import Ecto.Changeset 7 | 8 | defmodule PetParams do 9 | use Params.Schema 10 | 11 | schema do 12 | field(:name) 13 | field(:age, :integer) 14 | end 15 | end 16 | 17 | test "module has schema types" do 18 | assert %{age: :integer, name: :string, _id: :binary_id} == 19 | PetParams.__changeset__() 20 | end 21 | 22 | test "defaults to no required fields" do 23 | assert [] == Params.required(PetParams) 24 | end 25 | 26 | test "defaults to all optional fields" do 27 | # the order of the map fields is not guaranteed in OTP 26+ 28 | # https://www.erlang.org/news/164#maps 29 | assert [:_id, :age, :name] == Params.optional(PetParams) |> Enum.sort() 30 | end 31 | 32 | test "from returns a changeset" do 33 | ch = PetParams.from(%{}) 34 | assert %Changeset{} = ch 35 | end 36 | 37 | test "fields are castable" do 38 | ch = PetParams.from(%{"age" => "2"}) 39 | assert 2 = Changeset.get_change(ch, :age) 40 | end 41 | 42 | defmodule LocationParams do 43 | use Params.Schema 44 | @required ~w(latitude longitude) 45 | schema do 46 | field(:latitude, :float) 47 | field(:longitude, :float) 48 | end 49 | end 50 | 51 | defmodule BusParams do 52 | use Params.Schema 53 | @required ~w(origin destination) 54 | schema do 55 | embeds_one(:origin, LocationParams) 56 | embeds_one(:destination, LocationParams) 57 | end 58 | end 59 | 60 | test "invalid changeset on missing params" do 61 | assert %{valid?: false} = BusParams.from(%{}) 62 | end 63 | 64 | test "only valid if nested required present" do 65 | params = %{ 66 | "origin" => %{ 67 | "latitude" => 12.2, 68 | "longitude" => 13.3 69 | }, 70 | "destination" => %{ 71 | "latitude" => 12.2, 72 | "longitude" => 13.3 73 | } 74 | } 75 | 76 | assert %{valid?: true} = BusParams.from(params) 77 | end 78 | 79 | test "invalid if nested required missing" do 80 | params = %{ 81 | "origin" => %{ 82 | "latitude" => 12.2 83 | }, 84 | "destination" => %{ 85 | "longitude" => 13.3 86 | } 87 | } 88 | 89 | assert %{valid?: false} = BusParams.from(params) 90 | end 91 | 92 | test "to_map gets map of struct except for _id" do 93 | params = %{ 94 | "latitude" => 12.2, 95 | "longitude" => 13.3 96 | } 97 | 98 | result = 99 | params 100 | |> LocationParams.from() 101 | |> Params.to_map() 102 | 103 | assert result == %{latitude: 12.2, longitude: 13.3} 104 | end 105 | 106 | defparams( 107 | kitten(%{ 108 | breed!: :string, 109 | age_min: :integer, 110 | age_max: :integer, 111 | near_location!: %{ 112 | latitude: :float, 113 | longitude: :float 114 | } 115 | }) 116 | ) 117 | 118 | test "kitten module has list of required fields" do 119 | assert [:near_location, :breed] = Params.required(Params.ParamsTest.Kitten) 120 | end 121 | 122 | test "kitten module has list of optional fields" do 123 | # the order of the map fields is not guaranteed in OTP 26+ 124 | # https://www.erlang.org/news/164#maps 125 | assert [:age_max, :age_min] = Params.optional(Params.ParamsTest.Kitten) |> Enum.sort() 126 | end 127 | 128 | test "kitten method returns changeset" do 129 | assert %Changeset{} = kitten(%{}) 130 | end 131 | 132 | test "kitten returns valid changeset when all data is ok" do 133 | params = %{ 134 | "breed" => "Russian Blue", 135 | "age_min" => "0", 136 | "age_max" => "4", 137 | "near_location" => %{ 138 | "latitude" => "87.5", 139 | "longitude" => "-90.0" 140 | } 141 | } 142 | 143 | assert %Changeset{valid?: true} = kitten(params) 144 | end 145 | 146 | defparams( 147 | puppy(%{ 148 | breed!: :string, 149 | age_min: :integer, 150 | age_max: :integer, 151 | near_location!: {:embeds_one, LocationParams} 152 | }) 153 | ) 154 | 155 | test "puppy module has list of required fields" do 156 | assert [:near_location, :breed] = Params.required(Params.ParamsTest.Puppy) 157 | end 158 | 159 | test "puppy module has list of optional fields" do 160 | # the order of the map fields is not guaranteed in OTP 26+ 161 | # https://www.erlang.org/news/164#maps 162 | assert [:age_max, :age_min] = Params.optional(Params.ParamsTest.Puppy) |> Enum.sort() 163 | end 164 | 165 | test "puppy method returns changeset" do 166 | assert %Changeset{} = puppy(%{}) 167 | end 168 | 169 | test "puppy returns valid changeset when all data is ok" do 170 | params = %{ 171 | "breed" => "Russian Blue", 172 | "age_min" => "0", 173 | "age_max" => "4", 174 | "near_location" => %{ 175 | "latitude" => "87.5", 176 | "longitude" => "-90.0" 177 | } 178 | } 179 | 180 | assert %Changeset{valid?: true} = puppy(params) 181 | end 182 | 183 | defparams( 184 | dragon(%{ 185 | breed!: :string, 186 | age_min: :integer, 187 | age_max: :integer, 188 | near_locations!: {:embeds_many, LocationParams} 189 | }) 190 | ) 191 | 192 | test "dragon module has list of required fields" do 193 | assert [:near_locations, :breed] = Params.required(Params.ParamsTest.Dragon) 194 | end 195 | 196 | test "dragon module has list of optional fields" do 197 | # the order of the map fields is not guaranteed in OTP 26+ 198 | # https://www.erlang.org/news/164#maps 199 | assert [:age_max, :age_min] = Params.optional(Params.ParamsTest.Dragon) |> Enum.sort() 200 | end 201 | 202 | test "dragon method returns changeset" do 203 | assert %Changeset{} = dragon(%{}) 204 | end 205 | 206 | test "dragon returns valid changeset when all data is ok" do 207 | params = %{ 208 | "breed" => "Russian Blue", 209 | "age_min" => "0", 210 | "age_max" => "4", 211 | "near_locations" => [ 212 | %{ 213 | "latitude" => "87.5", 214 | "longitude" => "-90.0" 215 | }, 216 | %{ 217 | "latitude" => "67.5", 218 | "longitude" => "-60.0" 219 | } 220 | ] 221 | } 222 | 223 | assert %Changeset{valid?: true} = dragon(params) 224 | end 225 | 226 | defparams kid(%{ 227 | name: :string, 228 | age: :integer 229 | }) do 230 | def custom(ch, params) do 231 | cast(ch, params, ~w(name age)a) 232 | |> validate_required([:name]) 233 | |> validate_inclusion(:age, 10..20) 234 | end 235 | 236 | def changeset(ch, params) do 237 | cast(ch, params, ~w(name age)a) 238 | |> validate_inclusion(:age, 1..6) 239 | end 240 | end 241 | 242 | test "user can populate with custom changeset" do 243 | assert %{valid?: false} = kid(%{name: "hugo", age: 5}, with: &Params.ParamsTest.Kid.custom/2) 244 | end 245 | 246 | test "user can override changeset" do 247 | assert %{valid?: true} = kid(%{name: "hugo", age: 5}) 248 | end 249 | 250 | test "can obtain data from changeset" do 251 | m = Params.data(kid(%{name: "hugo", age: "5"})) 252 | assert "hugo" == m.name 253 | assert 5 == m.age 254 | assert nil == m._id 255 | end 256 | 257 | defmodule SearchUser do 258 | @schema %{ 259 | name: :string, 260 | near: %{ 261 | latitude: :float, 262 | longitude: :float 263 | } 264 | } 265 | 266 | use Params.Schema, @schema 267 | 268 | def changeset(ch, params) do 269 | cast(ch, params, ~w(name)a) 270 | |> validate_required([:name]) 271 | |> cast_embed(:near) 272 | end 273 | end 274 | 275 | test "can define a custom module for params schema" do 276 | assert %{valid?: false} = SearchUser.from(%{near: %{}}) 277 | end 278 | 279 | defmodule StringArray do 280 | use Params.Schema, %{tags!: [:string]} 281 | end 282 | 283 | test "can have param with array of strings" do 284 | assert %{valid?: true} = ch = StringArray.from(%{"tags" => ["hello", "world"]}) 285 | assert ["hello", "world"] = Params.data(ch).tags 286 | end 287 | 288 | defmodule ManyNames do 289 | use Params.Schema, %{names!: [%{name!: :string}]} 290 | end 291 | 292 | test "can have array of embedded schemas" do 293 | assert %{valid?: true} = ch = ManyNames.from(%{names: [%{name: "Julio"}, %{name: "Cesar"}]}) 294 | assert ["Julio", "Cesar"] = ch |> Params.data() |> Map.get(:names) |> Enum.map(& &1.name) 295 | end 296 | 297 | defmodule Vowel do 298 | use Params.Schema, %{x: :string} 299 | 300 | def changeset(ch, params) do 301 | cast(ch, params, [:x]) 302 | |> validate_required([:x]) 303 | |> validate_inclusion(:x, ~w(a e i o u)) 304 | end 305 | end 306 | 307 | test "module's data function returns {:ok, data} for valid changeset" do 308 | assert {:ok, %{__struct__: _, x: _}} = Vowel.data(%{"x" => "a"}) 309 | end 310 | 311 | test "module's data function returns {:error, changeset} for invalid changeset" do 312 | assert {:error, %Changeset{valid?: false}} = Vowel.data(%{"x" => "x"}) 313 | end 314 | 315 | defparams( 316 | schema_options(%{ 317 | foo: [field: :string, default: "FOO"] 318 | }) 319 | ) 320 | 321 | test "can specify raw Ecto.Schema options like default using a keyword list" do 322 | ch = schema_options(%{}) 323 | assert ch.valid? 324 | m = Params.data(ch) 325 | assert m.foo == "FOO" 326 | end 327 | 328 | test "gets default values with to_map" do 329 | changeset = schema_options(%{}) 330 | map = Params.to_map(changeset) 331 | assert map == %{foo: "FOO"} 332 | end 333 | 334 | defparams( 335 | default_nested(%{ 336 | foo: %{ 337 | bar: :string, 338 | baz: :string 339 | }, 340 | bat: %{ 341 | man: [field: :string, default: "BATMAN"], 342 | wo: %{ 343 | man: [field: :string, default: "BATWOMAN"] 344 | }, 345 | mo: %{vil: :string} 346 | } 347 | }) 348 | ) 349 | 350 | test "embeds with defaults are not nil" do 351 | ch = default_nested(%{}) 352 | assert ch.valid? 353 | m = Params.data(ch) 354 | assert m.bat.man == "BATMAN" 355 | assert m.bat.wo.man == "BATWOMAN" 356 | assert %{mo: nil} = m.bat 357 | assert nil == m.foo 358 | end 359 | 360 | test "to_map works on nested schemas with default values and empty input" do 361 | changeset = %{} |> default_nested 362 | 363 | assert changeset.valid? 364 | result = Params.to_map(changeset) 365 | 366 | assert result == %{ 367 | bat: %{ 368 | man: "BATMAN", 369 | wo: %{ 370 | man: "BATWOMAN" 371 | } 372 | } 373 | } 374 | end 375 | 376 | test "to_map works on nested schemas with default values" do 377 | changeset = 378 | %{ 379 | bat: %{ 380 | man: "Bruce" 381 | } 382 | } 383 | |> default_nested 384 | 385 | assert changeset.valid? 386 | result = Params.to_map(changeset) 387 | 388 | assert result == %{ 389 | bat: %{ 390 | man: "Bruce", 391 | wo: %{ 392 | man: "BATWOMAN" 393 | } 394 | } 395 | } 396 | end 397 | 398 | defmodule DefaultNested do 399 | use Params.Schema, %{ 400 | a: :string, 401 | b: :string, 402 | c: [field: :string, default: "C"], 403 | d: %{ 404 | e: :string, 405 | f: :string, 406 | g: [field: :string, default: "G"] 407 | }, 408 | h: %{ 409 | i: :string, 410 | j: :string, 411 | k: [field: :string, default: "K"] 412 | }, 413 | l: %{ 414 | m: :string 415 | }, 416 | n: %{ 417 | o: %{ 418 | p: [field: :string, default: "P"] 419 | } 420 | } 421 | } 422 | end 423 | 424 | test "to_map only returns submitted fields" do 425 | result = 426 | %{ 427 | a: "A", 428 | d: %{ 429 | e: "E", 430 | g: "g" 431 | } 432 | } 433 | |> DefaultNested.from() 434 | |> Params.to_map() 435 | 436 | assert result == %{ 437 | a: "A", 438 | c: "C", 439 | d: %{ 440 | e: "E", 441 | g: "g" 442 | }, 443 | h: %{ 444 | k: "K" 445 | }, 446 | n: %{ 447 | o: %{ 448 | p: "P" 449 | } 450 | } 451 | } 452 | end 453 | 454 | defmodule DefaultCountParams do 455 | use Params.Schema 456 | 457 | schema do 458 | field(:count, :integer, default: 1) 459 | end 460 | end 461 | 462 | test "use Params.Schema respects defaults" do 463 | changeset = DefaultCountParams.from(%{}) 464 | assert %{count: 1} = Params.to_map(changeset) 465 | end 466 | end 467 | --------------------------------------------------------------------------------