Last active
February 17, 2019 17:19
-
-
Save fieldstrength/b83cf70c4b819e9abf00c560bd960202 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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