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

change optionFromJson to enable it to handle undefined values #80

Merged
merged 3 commits into from
Jun 17, 2022
Merged
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
12 changes: 6 additions & 6 deletions src/Decco.re
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@ let optionToJson = (encoder, opt) =>
};

let optionFromJson = (decoder, json) =>
switch (Js.Json.decodeNull(json)) {
| Some(_) => Belt.Result.Ok(None)
| None => decoder(json) |> Belt.Result.map(_, v => Some(v))
switch (Js.Null_undefined.return(json) |> Js.Null_undefined.toOption) {
| None => Belt.Result.Ok(None)
| Some(json) => decoder(json) |> Belt.Result.map(_, v => Some(v))
};

let resultToJson = (okEncoder, errorEncoder, result) =>
Expand Down Expand Up @@ -155,10 +155,10 @@ let dictFromJson = (decoder, json) =>
->Belt.Array.reduce(Ok(Js.Dict.empty()), (acc, (key, value)) =>
switch (acc, decoder(value)) {
| (Error(_), _) => acc

| (_, Error({ path } as error)) => Error({...error, path: "." ++ key ++ path})
| (Ok(prev), Ok(newVal)) =>

| (Ok(prev), Ok(newVal)) =>
let () = prev->Js.Dict.set(key, newVal);
Ok(prev);
}
Expand Down
4 changes: 4 additions & 0 deletions test/__tests__/test.re
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ describe("option", () => {
describe("o_decode", () => {
describe("good", () => {
testGoodDecode("null", o_decode(s_decode), Js.Json.null, None);
testGoodDecode("undefined", o_decode(s_decode), [%raw {|undefined|}], None);
testGoodDecode("non-null", o_decode(s_decode), Js.Json.string("heyy"), Some("heyy"));
});

Expand Down Expand Up @@ -703,6 +704,9 @@ describe("record", () => {

let json = {|{"hey":"hey","other_key":"!"}|} |> Js.Json.parseExn;
testGoodDecode("missing optional", record_decode, json, { hey: "hey", opt: None, o: None, f: 1.0, otherKey: "!" });

let json: Js.Json.t = [%raw {|{"hey":"hey","other_key":"!","opt": undefined}|}]
testGoodDecode("optional field set to undefined", record_decode, json, { hey: "hey", opt: None, o: None, f: 1.0, otherKey: "!" });
});

describe("bad", () => {
Expand Down