Postgres-simple snaplet for showing dates in api

Filed under: programming

It took me a while to figure out how to get an API off the ground because I couldn’t find any ready examples of non-text types and had to search quite a bit. In summary here are the stuff that worked:

  • When the error says A web handler threw an exception. Details: UnexpectedNull {...} The keyword there was null so use Maybe types rather than Just types (matching types can be found here)
  • To render date types, define it as Maybe Day (or Date) then when serializing it to a Value type in toJSON… use a form like this to get a type allowed, see instances listed here: T.pack "last_used" .= show last_used
  • See this list of types for FromField to know what postgresql-simple can handle
-- Example of Types.hs

import qualified Data.Text as T
import           Data.Time.Calendar

data Clothing = Clothing
{  brand :: T.Text
 , size :: Maybe Int
 , last_worn :: Maybe Day

instance FromRow Clothing where
  fromRow = Clothing   field  field  field
instance ToJSON Clothing where
  toJSON (Clothing brand size last_worn) = object [
    "brand" .= brand
  , "size" .= size 
  , T.pack "last_worn" .= show last_worn