Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ToJSON instance for persistent Entity

Tags:

haskell

yesod

I'm trying to use the new selectRep function from Yesod 1.2, but I'm having trouble getting json responses to work.

instance ToJSON (Entity Feed) where
    toJSON (Entity uid (Feed url lastUpdated)) = object 
        [ "id" .= uid
        , "url" .= url
        , "lastUpdated" .= lastUpdated
        ]

getFeedByIdR :: FeedId -> Handler TypedContent
getFeedByIdR feedId = do
    feed <- runDB $ get404 feedId
    selectRep $ do
        provideRep $ return $ toJSON (Entity feedId feed)

The error I get from the above code is

Handler/Feed.hs:23:31:
    Overlapping instances for ToJSON (Entity Feed)
      arising from a use of `toJSON'
    Matching instances:
      instance ToJSON e => ToJSON (Entity e)
        -- Defined in `persistent-1.2.0.1:Database.Persist.Class.PersistEntity'
      instance ToJSON (Entity Feed) -- Defined at Handler/Feed.hs:5:10
    In the second argument of `($)', namely
      `toJSON (Entity feedId feed)'
    In the second argument of `($)', namely
      `return $ toJSON (Entity feedId feed)'
    In a stmt of a 'do' block:
      provideRep $ return $ toJSON (Entity feedId feed)

It seems that persistent does indeed provide an instance for ToJSON (Entity e) here, but can I use my ToJSON (Entity Feed) somehow?

like image 544
Kevin Avatar asked Sep 12 '26 02:09

Kevin


1 Answers

If you provide an instance for Feed, then you can use the built-in Entity e instance. Adding json to your entity line will create that instance automatically, see: https://github.com/yesodweb/persistent/wiki/Persistent-entity-syntax#json-instances

like image 115
Michael Snoyman Avatar answered Sep 15 '26 06:09

Michael Snoyman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!