0

我正在使用@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()调用中使用?

4

0 回答 0