mrkkrp / modern-uri

Modern library for working with URIs
Other
68 stars 18 forks source link

Add an `updateQueryParams` function #31

Closed joelmccracken closed 4 years ago

joelmccracken commented 4 years ago

Heya, thanks for the great library. Working with it I need to "update" the value of an existing QueryParam from a URI, and while writing a function to do this, it surprised me that something like it didn't exist in the library.

I'm not sure if you think this would be a nice thing to add to this library, or perhaps this is easy to do somehow with lenses (I do not know lenses very well, so it might be and I just don't know).

mrkkrp commented 4 years ago

I'd say that the easiest way to do it is with lenses. Can you show definition of the function you want to add?

joelmccracken commented 4 years ago

Something like this:

queryParamKey :: QueryParam -> RText 'QueryKey
queryParamKey qp =
  case qp of
    QueryFlag qk    -> qk
    QueryParam qk _ -> qk

updateURIQueryParam :: URI -> QueryParam -> URI
updateURIQueryParam uri qp = do
  let sameKey :: QueryParam -> QueryParam -> Bool
      sameKey qParam qParam' = queryParamKey qParam /= queryParamKey qParam'
  let replaceParam :: QueryParam -> [QueryParam] -> [QueryParam]
      replaceParam qParam qps = qParam : filter (sameKey qParam) qps
  uri & L.uriQuery %~ replaceParam qp

(I figured out the lenses stuff though I think this would actually add a dependency on the lens library so I assume you will want to change it)

mrkkrp commented 4 years ago

This is really something that is best done via lenses. I'd like to try to avoid adding ad-hoc functions like this.

You can use the microlens package which has no dependencies and includes the commonly useful functions of lens.