mrkkrp / req

An HTTP client library
Other
337 stars 40 forks source link

How to pass GET, POST as a parameter to my function? #79

Closed GildedHonour closed 4 years ago

GildedHonour commented 4 years ago

I have these functions which are identiacal except that one sends a GET request, the other POST one.

send1 :: IO BS.ByteString
send1 = do
    runReq defaultHttpConfig $ do
        result <- req GET (https "some_domain" /: "some_path") NoReqBody bsResponse getHeaders
        pure (responseBody result :: BS.ByteString)

    -- [some stuff...]

send2 :: IO BS.ByteString
send2 = do
    runReq defaultHttpConfig $ do
        result <- req POST (https "some_domain" /: "some_path") NoReqBody bsResponse getHeaders
        pure (responseBody result :: BS.ByteString)

    -- [some stuff]

I want to pass GET and POST as a parameter and thus merge the functions into a single one. I haven't found a way.

Later on I might want to add PUT and DELETE too. For now I need only GET and POST

GET and POST are both distinct data types in the library.

    data GET = GET
    data POST = POST

The HttpMethod class won't help either - it won't compile:

    send1 :: (HttpMethod meth) => meth -> IO BS.ByteString
    send1 meth = do
        runReq defaultHttpConfig $ do
            result <- req meth (https "some_domain" /: "some_path") NoReqBody bsResponse getHeaders
            pure (responseBody result :: BS.ByteString)

I don't want to create yet another new data type - MyHttpMethod, as a workaround, that'll have 2 constructors - GET and POST. I don't want to introduce new types.

Then how else?

mrkkrp commented 4 years ago

Why doesn't it work with HttpMethod?

GildedHonour commented 4 years ago
  • Could not deduce: HttpBodyAllowed (AllowsBody me) 'NoBody
        arising from a use of ‘req’
      from the context: HttpMethod me
        bound by the type signature for:
                   send12 :: forall me.
                            HttpMethod me => [..........]
mrkkrp commented 4 years ago

Then add HttpBodyAllowed (AllowsBody me) 'NoBody as a constraint to your function.

GildedHonour commented 4 years ago

Thanks.