I try to generalize the URL handling when going to for example /api/v1.0/events?order=-id,title
for a RESTful output - so the results will order by id
desc, and than by title
asc
Models file:
-- models
Event
title Text
content Text
userId UserId
deriving Eq
deriving Show
Haskell file:
-- Events.hs
text2Order :: Text -> [SelectOpt Event]
text2Order text =
case lookup textWithNoPrefix keyVal of
Just val -> [direction val]
Nothing -> error "wrong order"
where
keyVal = [ ("title", EventTitle)
, ("user" , EventUserId)
, ("id" , EventId)
]
textWithNoPrefix = if T.isPrefixOf "-" text
then T.tail text
else text
direction = if T.isPrefixOf "-" text
then Desc
else Asc
I seem to have two problems:
- Compiler doesn't like
keyVal
as its a list of tuple, where the 2nd value is different - Even though I assign
Asc
orDesc
todirection
the complier doesn't accept it
The problem is that
EventTitle
andEventUserId
are of different types, so you can't put the two of them in the same list. You can, however, putEventTitle
andEventContent
in the same list -- they both have typeEntityField Event Text
.However, an approach like the following should work (using the Person example from the Yesod tutorial):
You can factor out the +/- processing like this:
If you want to perform error processing, return a
Maybe (SelectOpt Person)
:and then:
The result will be
Just [...]
if all of the pairs are valid andNothing
if any one of them isn't recognized.Update
Here is another approach using existential types which looks a lot more like your code: