Skip to content

Commit

Permalink
Merge pull request #80 from draftbit/handle-undefined-as-null
Browse files Browse the repository at this point in the history
change optionFromJson to enable it to handle undefined values
  • Loading branch information
ryb73 authored Jun 17, 2022
2 parents f8bb65a + 5e8f0b2 commit 2051c37
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
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

0 comments on commit 2051c37

Please sign in to comment.