我正在使用@glennsl 的bs-json
模块来解码一些 JSON 响应,但是所有 JSON 响应除了它们独特的有效负载之外还有一些公共字段。此外,JSON 响应(通过 XMLHTTPRequest)根据它们是否成功而有所不同:它们不包含该'body
元素。
我想知道是否有一种方法可以创建方法来采用通用格式的解码器。我的想法是这样的:
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)
}
}
};
}
有没有办法在reasonml中制作模板方法?或者,应该只将类型包装'body
在一个option
元素中并optional()
在field()
调用中使用?