on 134ddcf help sign in
rel8/src/Rel8/Type/JSONEncoded.hs
38 lines 1.0 kB history raw
1module Rel8.Type.JSONEncoded ( JSONEncoded(..) ) where
3-- aeson
4import Data.Aeson ( FromJSON, ToJSON, parseJSON, toJSON )
5import Data.Aeson.Types ( parseEither )
7-- base
8import Prelude
10-- rel8
11import Rel8.Type ( DBType(..) )
12import Rel8.Type.Information ( parseTypeInformation )
15-- | A deriving-via helper type for column types that store a Haskell value
16-- using a JSON encoding described by @aeson@'s 'ToJSON' and 'FromJSON' type
17-- classes.
18--
19-- The declaration:
20--
21-- >>> import Data.Aeson
22--
23-- >>> :{
24-- data Pet = Pet { petName :: String, petAge :: Int }
25-- deriving (Generic, ToJSON, FromJSON)
26-- deriving PrimitiveType via JSONEncoded Pet
27-- :}
28--
29-- will allow you to store @Pet@ values in a single SQL column (stored as
30-- @json@ values).
31newtype JSONEncoded a = JSONEncoded { fromJSONEncoded :: a }
34instance (FromJSON a, ToJSON a) => DBType (JSONEncoded a) where
35 typeInformation = parseTypeInformation f g typeInformation
36 where
37 f = fmap JSONEncoded . parseEither parseJSON
38 g = toJSON . fromJSONEncoded