Skip to content

Instantly share code, notes, and snippets.

@rpereira
Last active May 29, 2017 16:40
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 rpereira/a44b415956e27712f58f88d3c5a3fb0c to your computer and use it in GitHub Desktop.
Save rpereira/a44b415956e27712f58f88d3c5a3fb0c to your computer and use it in GitHub Desktop.
Customize JSON instances
-- | Goal is not to expose sensitive user data such as the field email.
--
-- When creating the user, the request body only has: username, email, bio (optional), image (optional)
-- When returning the user, I only want to show: username, bio, image.
--
-- Error:
-- /Users/rap/code/thesis/ninja/src/Api.hs:52:11: error:
-- • No instance for (aeson-1.0.2.1:Data.Aeson.Types.ToJSON.ToJSON
-- (persistent-2.6.1:Database.Persist.Class.PersistEntity.Entity
-- Models.User.User))
-- arising from a use of ‘serve’
-- • In the expression: serve appApi (appToServer cfg)
-- In an equation for ‘app’: app cfg = serve appApi (appToServer cfg)
--
-- I'm a bit puzzled by this.
--
-- I came acrros this wiki entry, but I can't understand how to use mpsEntityJSON.
-- https://github.com/yesodweb/persistent/wiki/Persistent-entity-syntax#json-instances
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
User sql=users
username Text
email Text
bio Text Maybe default=NULL
image Text Maybe default=NULL
createdAt UTCTime default=now()
updatedAt UTCTime Maybe default=NULL
UniqueUser username email
deriving Show Generic
|]
instance FromJSON User where
parseJSON = withObject "User" $ \ v ->
User <$> v .: "username"
<*> v .: "email"
<*> v .:? "bio"
<*> v .:? "image"
<*> v .: "createdAt"
<*> v .:? "updatedAt"
instance ToJSON User where
toJSON User {userUsername, userBio, userImage} =
object [ "username" .= userUsername
, "bio" .= userBio
, "image" .= userImage
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment