~alcinnz/amphiarao

ref: ea181da2a6b756e80efdd78197de77d51edb2adc amphiarao/src/JSON.hs -rw-r--r-- 1.2 KiB
ea181da2 — Adrian Cochrane Add support for <select> in forms. 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, DeriveGeneric #-}
module JSON(getJSON, okJSON, errJSON) where

import Happstack.Lite
import Happstack.Server.Types (unBody, takeRequestBody)
import Happstack.Server (askRq, resp)

import Data.Aeson
import Data.Text (Text)
import GHC.Generics
import Data.ByteString.Lazy (ByteString)

import Control.Monad.IO.Class (liftIO)

getBody :: ServerPart ByteString
getBody = do
    req  <- askRq
    body <- liftIO $ takeRequestBody req
    case body of
        Just rqbody -> return . unBody $ rqbody
        Nothing     -> return ""

getJSON :: FromJSON x => ServerPart (Maybe x)
getJSON = decode <$> getBody

okJSON :: ToJSON x => x -> ServerPart Response
okJSON x = do
    setHeaderM "Content-Type" "application/json"
    ok $ toResponse $ encode x

data WDError' = WDError' {
    value :: WDError
  } deriving Generic
instance ToJSON WDError'
data WDError = WDError {
    error :: Text,
    message :: String,
    stacktrace :: Text -- Noop
  } deriving Generic
instance ToJSON WDError

errJSON :: Int -> Text -> String -> ServerPart Response
errJSON code name message = do
    setHeaderM "Content-Type" "application/json"
    resp code $ toResponse $ encode $ WDError' $ WDError name message ""