-
Notifications
You must be signed in to change notification settings - Fork 3
/
option.gleam
56 lines (52 loc) · 1.23 KB
/
option.gleam
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import gleam/option.{type Option, None, Some}
import valid/common.{type Validator}
fn is_some_check(maybe: Option(value)) -> Option(value) {
case maybe {
None -> None
Some(value) -> Some(value)
}
}
/// Validate that a value is not None.
/// Returns the value if Some.
///
/// ## Example
///
/// type PersonInput { PersonInput(name: Option(String)) }
///
/// type PersonValid { PersonValid(name: String) }
///
/// let validator = fn(person) {
/// v.build1(PersonValid)
/// |> v.validate(person.name, option.is_some("Name is null"))
/// }
///
pub fn is_some(error: e) -> Validator(Option(i), i, e) {
common.custom(error, is_some_check)
}
/// Validate an optional value.
///
/// Run the validator only if the value is Some.
/// If the value is None then just return None back.
///
/// ## Example
///
/// let validator = fn(person) {
/// v.build1(PersonValid)
/// |> v.validate(
/// person.name,
/// option.optional(string.min_length("Short", 3))
/// )
/// }
///
pub fn optional(validator: Validator(input, input, error)) {
fn(maybe: Option(input)) {
case maybe {
None -> Ok(maybe)
Some(value) ->
case validator(value) {
Ok(_) -> Ok(maybe)
Error(error) -> Error(error)
}
}
}
}