After a bit of trial and error I managed to create the following function in Yesod to grab an object from a JSON POST, create an EventFolder entity, and 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, well, first, is there a more concise way to write this function–it seems rather long-winded. And second, how could I extract a function that generically creates an object from the JSON? So I’d like to end up with something like
postAddEventFolderR = do
v1 = extractEntityFromJsonPost (whatever params) :: EventFolder
runDB $ insert $ v1
return $ RepJson $ toContent $ show v1
Note I’m completely new to Haskell.
I think the function you’re looking for is parseJsonBody_. Additionally, instead of using
toContentandshow, I think you’d want to use jsonToRepJson. So all together, you can probably express your code as:Though I’m not entirely certain why you’re responding with the data that the client just submitted.