Skip to content

Commit

Permalink
Add doc for required
Browse files Browse the repository at this point in the history
  • Loading branch information
sporto committed Jun 29, 2024
1 parent 3bd0d5d commit ee80ffb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
26 changes: 22 additions & 4 deletions src/valid.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,30 @@ pub fn required_in_dict(
required(accumulator, input, get, access_error, validator)
}

/// Validate an attribute required in an arbitrary data type
/// Here you provide your own accessor
/// The accessor should return `Option(property)`
///
/// ## Example
///
/// let get_name = fn(d) { dict.get(d, "name") |> option.from_result }
///
/// let validator = fn(dictionary: Dict(String, String)) {
/// valid.build1(Person)
/// |> valid.required(
/// from: dictionary,
/// get: get_name,
/// missing: "Missing name",
/// validator: valid.string_is_not_empty(ErrorEmpty)
/// )
/// }
///
pub fn required(
accumulator: Result(fn(b) -> next_accumulator, Errors(e)),
input: input,
get: fn(input) -> Option(a),
access_error: e,
validator: fn(a) -> Result(b, Errors(e)),
from input: input,
get get: fn(input) -> Option(a),
missing access_error: e,
validator validator: fn(a) -> Result(b, Errors(e)),
) {
case get(input) {
Some(a) -> validate(accumulator, a, validator)
Expand Down
6 changes: 4 additions & 2 deletions test/valid_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -121,16 +121,18 @@ pub fn custom_test() {
fn user_dict_validator(
input: Dict(String, String),
) -> ValidatorResult(ValidUser, String) {
let get_email = fn(d) { dict.get(d, "email") |> option.from_result }

valid.build3(ValidUser)
|> valid.required_in_dict(
from: input,
get: "name",
missing: "Missing name",
validator: valid.string_is_not_empty("Please provide a name"),
)
|> valid.required_in_dict(
|> valid.required(
input,
"email",
get_email,
"Missing email",
valid.string_is_email("Please provide an email"),
)
Expand Down

0 comments on commit ee80ffb

Please sign in to comment.