How can I extract "extractEntityFromPostedJson" in Yesod?

After several trial and error, I managed to create the following function in Yesod to capture an object from POST JSON, create an object EventFolderand save it to the database.

postAddEventFolderR :: Handler RepJson
postAddEventFolderR = do
    r <- waiRequest 
    v <- liftIO . runResourceT $ requestBody r $$ sinkParser json
    let v1 :: EventFolder
        v1 = case fromJSON v of
                 Success a -> a
                 Error s   -> error s
    runDB $ insert $ v1
    return $ RepJson $ toContent $ show v1

The test function looks like curl -H "Content-Type: application/json" -X POST -d '{"name":"test_folder"}' http://localhost:5000/AddEventFolder.

The question is, firstly, there is a more concise way to write this function - it seems rather protracted. Secondly, how can I extract a function that generally creates an object from JSON? So I would like to get something like

postAddEventFolderR = do
    v1 = extractEntityFromJsonPost (whatever params) :: EventFolder
    runDB $ insert $ v1
    return $ RepJson $ toContent $ show v1

Note. I am completely new to Haskell.

+3
source share
1 answer

, , , parseJsonBody_. , toContent show, , jsonToRepJson. , , , , :

postAddEventFolderR = do
    v <- parseJsonBody_
    runDB $ insert (v :: EventFolder)
    jsonToRepJson v

, , .

+4

All Articles