I'm using @glennsl's bs-json
module to decode some JSON responses, but all the JSON responses have some common fields in addition to their unique payload. Furthermore, the JSON responses (via XMLHTTPRequest) are different depending on whether they're successful or not: they wouldn't include the 'body
element.
I'm wondering if there's a way I can create method to take on a decoder for the generalized format. I was think something along the lines of:
module Decode {
type msgCheck = {
success: bool,
command: string,
errmsg: string,
errnum: int,
};
// type msgComplete('body) = {
// success: bool,
// command: string,
// errmsg: string,
// errnum: int,
// body: 'body, /* This is what the incoming JSON looks like. */
// }
let msgCheck = json => Json.Decode.{
success: json |> field("success", bool),
command: json |> field("command", string),
errmsg: json |> field("error_string", string),
errnum: json |> field("error", int),
};
let jsonDecode = ('body, bodyDecoder, response) => {
let msgCheck = response -> msgCheck;
switch msgCheck.success {
| true => {
let (r:'body) = response -> bodyDecoder;
return (true, Some(r)) /* returning body (only) preferable. */
}
| false => {
Js.log(msgCheck.errmsg);
return (false, None)
}
}
};
}
Is there a way make a template method in reasonml? Or, should just wrap the 'body
type in an option
element and use optional()
in the field()
calls?