Skip to content

Instantly share code, notes, and snippets.

@Woody88
Created March 15, 2018 18:46
Show Gist options
  • Save Woody88/9205cd16357c73be11a12d7ebe6d70f4 to your computer and use it in GitHub Desktop.
Save Woody88/9205cd16357c73be11a12d7ebe6d70f4 to your computer and use it in GitHub Desktop.
import Data.Aeson
import Web.HttpApiData (ToHttpApiData(..))
instance FromJSON SFId where
parseJSON = withText "Id" $ \i -> do
return $ SFId i
instance ToJSON SFId where
toJSON (SFId i) = object
[ "Id" .= i ]
instance ToHttpApiData SFId where
toQueryParam (SFId id) = id
-- Now the user can set their adts id field with wtv name they want.
data Account = Account
{ accountId :: SFId
, name :: Text
} deriving (Generic, Show)
instance FromJSON Account
instance ToJSON Account
--- This will also automatically handle the SFId for the user. However, I had to create my own FromJSON class because
--- Salesforce returns other fields that end user will not need.
--- Example of a reponse when making a get: {attributes: {type: "foo", url:"random"}, Id: "sad2313sda", Name: "new Account"}
--- My own FromJSON class removes the unedded fields and formats fields name to meet salesforce naming convention. Salesforce naming convention for fields starts with capital letters and
--- mixes it with camelCamel cases. I.E: AccountName, AccountNumber
class (Generic a, GFromJSON Zero (Rep a)) => HFFromJSON a where
myFromJSON :: Value -> Parser a
myFromJSON (Object v) = genericParseJSON defaultOptions { fieldLabelModifier = firstCharToUpper} v'
where v' = Object (HMS.delete "attributes" $ v) :: Value
class (Typeable a, Generic a, GToJSON Zero (Rep a)) => HFToJSON a where
myToJSON :: a -> Value
myToJSON = genericToJSON defaultOptions { fieldLabelModifier = capitalized }
capitalized :: String -> String
capitalized [] = []
capitalized (head:tail) = Char.toUpper head : lowered tail
where
lowered [] = []
lowered (head:tail) = Char.toLower head : lowered tail
firstCharToUpper :: String -> String
firstCharToUpper (head:tail) = Char.toUpper head : tail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment