Skip to content
Permalink
Browse files

posts: create post via json

  • Loading branch information...
3v0k4 committed Aug 17, 2019
1 parent cd78427 commit 4922c8db2706fd0999ef478373b82326f5851b4d
Showing with 24 additions and 1 deletion.
  1. +1 −1 config/routes
  2. +23 −0 src/Handler/Posts.hs
@@ -16,4 +16,4 @@
/posts PostsR GET POST
/posts/#PostId PostR DELETE

/api/posts ApiPostsR GET
/api/posts ApiPostsR GET POST
@@ -11,6 +11,7 @@ module Handler.Posts where
import Import
import qualified Database.Esqueleto as E
import Database.Esqueleto ((^.))
import Data.Aeson.Types (Result(..), Parser, parseEither, withObject)

postForm :: UserId -> Form Post
postForm userId =
@@ -72,6 +73,28 @@ getApiPostsR = do
let allPosts' = PostData <$> allPosts
return $ object [ "posts" .= allPosts' ]

postApiPostsR :: Handler Value
postApiPostsR = do
(result :: Result Value) <- parseCheckJsonBody
case result of
Success val -> do
let mPost = parseEither postParser val
case mPost of
Right post -> do
postId <- runDB $ insert post
return $ object [ "post" .= post, "id" .= postId ]
Left err ->
invalidArgs [pack err]
Error err ->
invalidArgs [pack err]

postParser :: Value -> Parser Post
postParser = withObject "Post" (\obj -> do
title <- obj .: "title"
text <- obj .: "text"
userId <- obj .: "userId"
return $ Post title text userId)

postPostsR :: Handler Html
postPostsR = do
userId <- fmap fst $ requireAuthPair

0 comments on commit 4922c8d

Please sign in to comment.
You can’t perform that action at this time.