Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional_subfield decoder #792

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/gleam/dynamic/decode.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,48 @@ pub fn optional_field(
})
}

/// The same as [`optional_field`](#optional_field), except taking a path to
/// the value rather than a field name.
///
/// This function will index into dictionaries with any key type, and if the
/// key is an int then it'll also index into Erlang tuples and JavaScript
/// arrays, and the first two elements of Gleam lists.
///
/// # Examples
///
/// ```gleam
/// let data = dynamic.from(dict.from_list([
/// #("data", dict.from_list([
/// #("name", "Lucy"),
/// ]))
/// ]))
///
/// let decoder = {
/// use name <- decode.subfield(["data", "name"], decode.string)
/// use email <- decode.optional_subfield(["data", "email"], "n/a", decode.string)
/// decode.success(SignUp(name: name, email: email))
/// }
///
/// let result = decode.run(data, decoder)
/// assert result == Ok(SignUp(name: "Lucy", email: "n/a"))
/// ```
///
pub fn optional_subfield(
field_path: List(name),
default: t,
field_decoder: Decoder(t),
next: fn(t) -> Decoder(final),
) -> Decoder(final) {
Decoder(function: fn(data) {
let #(out, errors1) =
index(field_path, [], field_decoder.function, data, fn(_, _) {
#(default, [])
})
let #(out, errors2) = next(out).function(data)
#(out, list.append(errors1, errors2))
})
}

/// A decoder that decodes a value that is nested within other values. For
/// example, decoding a value that is within some deeply nested JSON objects.
///
Expand Down
104 changes: 104 additions & 0 deletions test/gleam/dynamic/decode_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,110 @@ pub fn optionally_at_no_path_error_test() {
|> should.equal(100)
}

pub fn optional_subfield_dict_string_ok_test() {
let data =
dynamic.from(
dict.from_list([
#(
"first",
dict.from_list([#("second", dict.from_list([#("third", 1337)]))]),
),
]),
)

let decoder = {
use decoded <- decode.optional_subfield(
["first", "second", "third"],
100,
decode.int,
)

decode.success(decoded)
}

decode.run(data, decoder)
|> should.be_ok
|> should.equal(1337)
}

pub fn optional_subfield_dict_int_ok_test() {
let data =
dynamic.from(
dict.from_list([
#(10, dict.from_list([#(20, dict.from_list([#(30, 1337)]))])),
]),
)

let decoder = {
use decoded <- decode.optional_subfield([10, 20, 30], 123, decode.int)
decode.success(decoded)
}

decode.run(data, decoder)
|> should.be_ok
|> should.equal(1337)
}

pub fn optional_subfield_tuple_int_ok_test() {
let data = dynamic.from(#("x", #("a", "b", "c"), "z"))

let decoder = {
use decoded <- decode.optional_subfield([1, 0], "something", decode.string)
decode.success(decoded)
}

decode.run(data, decoder)
|> should.be_ok
|> should.equal("a")
}

pub fn optional_subfield_wrong_inner_error_test() {
let data =
dynamic.from(
dict.from_list([
#(
"first",
dict.from_list([#("second", dict.from_list([#("third", 1337)]))]),
),
]),
)

let decoder = {
use decoded <- decode.optional_subfield(
["first", "second", "third"],
"default",
decode.string,
)

decode.success(decoded)
}

decode.run(data, decoder)
|> should.be_error
|> should.equal([DecodeError("String", "Int", ["first", "second", "third"])])
}

pub fn optional_subfield_no_path_error_test() {
let data =
dynamic.from(
dict.from_list([#("first", dict.from_list([#("third", 1337)]))]),
)

let decoder = {
use decoded <- decode.optional_subfield(
["first", "second", "third"],
100,
decode.int,
)

decode.success(decoded)
}

decode.run(data, decoder)
|> should.be_ok
|> should.equal(100)
}

@external(erlang, "maps", "from_list")
@external(javascript, "../../gleam_stdlib_test_ffi.mjs", "object")
fn make_object(items: List(#(String, t))) -> Dynamic
Expand Down