Skip to content

Instantly share code, notes, and snippets.

@fieldstrength
Last active February 17, 2019 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fieldstrength/b83cf70c4b819e9abf00c560bd960202 to your computer and use it in GitHub Desktop.
Save fieldstrength/b83cf70c4b819e9abf00c560bd960202 to your computer and use it in GitHub Desktop.
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
module API.Types.Deriving where
import Data.Aeson
import Data.Aeson.Casing
import GHC.Generics
import Data.Proxy
import qualified Data.ByteString.Lazy.Char8 as BSC
newtype APIEncoding j a = APIEncoding { unAPIEncoding :: a } deriving Functor
class JSONEncoding j where
jsonEncoding :: proxy j -> Options
instance
( JSONEncoding j
, Generic a
, GFromJSON Zero (Rep a))
=> FromJSON (APIEncoding j a) where
parseJSON = fmap APIEncoding . genericParseJSON (jsonEncoding $ Proxy @ j)
instance
( JSONEncoding j
, Generic a
, GToJSON Zero (Rep a))
=> ToJSON (APIEncoding j a) where
toJSON = genericToJSON (jsonEncoding $ Proxy @ j) . unAPIEncoding
data SnakeCaseDropPrefix
instance JSONEncoding SnakeCaseDropPrefix where
jsonEncoding _ = aesonPrefix snakeCase
data Example = Example
{ exampleAccountId :: Int
, exampleAccountName :: String
} deriving stock (Show, Read, Eq, Ord, Generic)
deriving (ToJSON, FromJSON) via APIEncoding SnakeCaseDropPrefix Example
-- Example 5 "foo" ==> {"account_id":5,"account_name":"foo"}
doit :: IO ()
doit = BSC.putStrLn . encode $ Example 5 "foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment