使用条件查询参数构建URL

时间:2018-12-12 09:28:53

标签: functional-programming elm

我有一个简单的网址生成器,如下所示:

prepareUrl : Params -> String
prepareUrl params = 
   Url.crossOrigin "http://someapi.com/"
    ["posts"]
    [ 
    , Url.string "currency" params.currency
    , Url.string "members[0][birthday]" "12.12.1989"
    ]

当我收到诸如memberCount 2或3等之类的参数时,我需要像这样在请求中“克隆” members []:

params.membersCount = 3

prepareUrl : Params -> String
    prepareUrl params = 
       Url.crossOrigin "http://someapi.com/"
        ["posts"]
        [ 
        , Url.string "currency" params.currency
        , Url.string "members[0][birthday]" "12.12.1989"
        , Url.string "members[1][birthday]" "12.12.1989"
        , Url.string "members[2][birthday]" "12.12.1989"
        ]

日期字符串本身可以保持不变,没关系。我该怎么办?

1 个答案:

答案 0 :(得分:6)

由于Url.Builder.crossOrigin的第三个参数采用了QueryParameter值的列表,因此您可以使用0建立从memberCountList.range的列表:

prepareUrl : Params -> String
prepareUrl params = 
   Url.crossOrigin "http://someapi.com/"
    ["posts"]
    (Url.string "currency" params.currency :: birthdayParams params.memberCount)

birthdayParams : Int -> List Url.QueryParameter
birthdayParams memberCount =
    List.range 0 (memberCount - 1)
        |> List.map (\i -> Url.string ("members[" ++ String.fromInt i ++ "][birthday]") "12.12.1989")