From abaaf1c3011d7a995dcb344b83ed1698ea7ffd9d Mon Sep 17 00:00:00 2001 From: Filip Gralinski Date: Mon, 12 Oct 2020 07:27:32 +0200 Subject: [PATCH] Add sample JSON API for listing challenges --- Foundation.hs | 1 + Handler/ListChallenges.hs | 20 +++++++++++++++++++- config/routes | 1 + 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Foundation.hs b/Foundation.hs index b1ba47a..d1b3cf3 100644 --- a/Foundation.hs +++ b/Foundation.hs @@ -152,6 +152,7 @@ instance Yesod App where isAuthorized QueryFormR _ = regularAuthorization isAuthorized (QueryResultsR _) _ = regularAuthorization isAuthorized ListChallengesR _ = regularAuthorization + isAuthorized ListChallengesJsonR _ = regularAuthorization isAuthorized (ViewVariantR _ ) _ = regularAuthorization isAuthorized (ViewVariantTestR _ _) _ = regularAuthorization diff --git a/Handler/ListChallenges.hs b/Handler/ListChallenges.hs index 682eacc..922a3cf 100644 --- a/Handler/ListChallenges.hs +++ b/Handler/ListChallenges.hs @@ -2,12 +2,30 @@ module Handler.ListChallenges where import Import +mainCondition :: [Filter Challenge] +mainCondition = [ChallengeArchived !=. Just True] + getListChallengesR :: Handler Html -getListChallengesR = generalListChallenges [ChallengeArchived !=. Just True] +getListChallengesR = generalListChallenges mainCondition + +getListChallengesJsonR :: Handler Value +getListChallengesJsonR = generalListChallengesJson mainCondition getListArchivedChallengesR :: Handler Html getListArchivedChallengesR = generalListChallenges [ChallengeArchived ==. Just True] +instance ToJSON (Entity Challenge) where + toJSON (Entity _ ch) = object + [ "link" .= ("/challenge/" <> (challengeName ch)) + , "title" .= challengeTitle ch + , "description" .= challengeDescription ch + ] + +generalListChallengesJson :: [Filter Challenge] -> Handler Value +generalListChallengesJson filterExpr = do + challenges <- getChallenges filterExpr + return $ toJSON challenges + generalListChallenges :: [Filter Challenge] -> Handler Html generalListChallenges filterExpr = do challenges <- getChallenges filterExpr diff --git a/config/routes b/config/routes index 2d2bffb..3910c4a 100644 --- a/config/routes +++ b/config/routes @@ -10,6 +10,7 @@ /view-progress/#Int ViewProgressR GET /open-view-progress/#Int OpenViewProgressR GET /list-challenges ListChallengesR GET +/api/list-challenges ListChallengesJsonR GET /list-archived-challenges ListArchivedChallengesR GET /challenge-image/#ChallengeId ChallengeImageR GET