嵌套Suave WebPart

时间:2017-07-19 12:12:43

标签: rest f# suave

我第一次一直在玩Suave,显然有一些我不明白的东西。 我想要实现的是实现一个简单的Rest API:

  • 用户可以获得有关金融工具的信息
  • 此外,每个工具都有一个价格清单

为简单起见,我现在只专注于GET方法。

我的 非常 基本代码在这里:

[<AutoOpen>]
module RestFul =    

    let JSON v =     
        let jsonSerializerSettings = new JsonSerializerSettings()
        jsonSerializerSettings.ContractResolver <- new CamelCasePropertyNamesContractResolver()

        JsonConvert.SerializeObject(v, jsonSerializerSettings)
        |> OK 
        >=> Writers.setMimeType "application/json; charset=utf-8"

    let fromJson<'a> json =
        JsonConvert.DeserializeObject(json, typeof<'a>) :?> 'a    

    let getResourceFromReq<'a> (req : HttpRequest) = 
        let getString rawForm = System.Text.Encoding.UTF8.GetString(rawForm)
        req.rawForm |> getString |> fromJson<'a>

    type RestResource<'a> = {
        GetById : int -> 'a option
        GetPricesById : int -> 'a option
    }

    let rest resource =

        let handleResource requestError = function
            | Some r -> r |> JSON
            | _ -> requestError

        let getResourceById = 
            resource.GetById >> handleResource (NOT_FOUND "Resource not found")

        let getPricesById = 
            resource.GetPricesById >> handleResource (NOT_FOUND "Resource not found")

        choose [
            GET >=> pathScan "/instrument/%d" getResourceById
            GET >=> pathScan "/instrument/%d/prices" getPricesById
        ]


module Main =
    [<EntryPoint>]
    let main argv = 

        let webPart = rest {
                GetById = fun i -> Some i // placeholder
                GetPricesById = fun i -> Some i // placeholder, it'll be a list eventually
            }

        startWebServer defaultConfig webPart
        0

当我以这种方式定义WebPart时:

choose [
    GET >=> pathScan "/instrument/%d" getResourceById // Returns the instrument static data
    GET >=> pathScan "/instrument/%d/prices" getPricesById // Returns price list for the instrument
]

然后一切正常。我想知道是否有办法嵌套webparts,例如像这样:

// My idea about the code - doesn't compile
choose [
    pathScan "/instrument/%d" getResourceById >=> choose [
        GET // Returns the instrument static data
        GET >=> path "/prices" >=> (somehow refer to the previous id and get prices)  // Returns price list for the instrument
    ]
]

另外 - 当我了解RestAPI时,我的推理可能存在差距。我认为以这种方式嵌套价格终点可以清楚地表明价格被认为是一种工具的属性(如果我错了,请随时纠正我。)

1 个答案:

答案 0 :(得分:4)

是的,因此访问先前的请求有点反对;)我们希望事情能够独立发生,而不管刚刚发生了什么。因此,或许更好的解决方法是将价格简单地追加到路径的末端?

ART