Search code examples
haskellcabalghci

Couldn't match type ‘Text’ with ‘Key Todos’ arising from a use of ‘TodosId’


I try to create a Scotty Web app with CRUD operations. I can do the get operation to fetch all the todos list

getTodos :: ActionM ()
getTodos = do
  (todos :: [Entity Todos]) <-
    liftIO $ inBackend $ selectList [] []
  json todos

But I am blocked in my get operation to fetch only one item by id (which is a uuid value)

getTodo :: ActionM ()
getTodo = do
  (id :: Text) <- param "id"
  (todos :: [Entity Todos]) <-
    liftIO $ inBackend $ selectList [TodosId ==. id][]
  json todos

I got this message from "cabal run" command:

app/Main.hs:133:38: error:
    • Couldn't match type ‘Text’ with ‘Key Todos’
        arising from a use of ‘TodosId’
    • In the first argument of ‘(==.)’, namely ‘TodosId’
      In the expression: TodosId ==. id
      In the first argument of ‘selectList’, namely ‘[TodosId ==. id]’

I have tried to find a code to create a Persistent "Key" value to use in "selectList [TodosId ==. id][]" but all my test failed.

I am using

Cabal ==3.8.1.0,
scotty ==0.20.1,
persistent ==2.14.6.0,
persistent-postgresql ==2.13.6.1,

Solution

  • I want to share the solution:

    import Data.Maybe (fromJust)
    import Web.PathPieces
    
    parseNewsId :: Text -> TodosId
    parseNewsId =
        fromJust . fromPathPiece
    
    getTodo :: ActionM ()
    getTodo = do
      (id :: Text) <- param "id"
      (todos :: [Entity Todos]) <-
        liftIO $ inBackend $ selectList [TodosId ==. (parseNewsId id)][]
      json todos
    

    And can get the result as expected

    [
        {
            "description": "it is awesome",
            "id": "4754e8n7-6e5c-1234-7894-9312071db111",
            "is_done": false,
            "name": "Do exercice haskell"
        }
    ]
    

    Thanks for your attention!