packages feed

morley-client-0.3.2: src/Morley/Client/RPC/Aeson.hs

-- SPDX-FileCopyrightText: 2020 Tocqueville Group
--
-- SPDX-License-Identifier: LicenseRef-MIT-TQ

-- | Helpers for the @aeson@ package.
--
-- Currently we need this module due to "GHC stage restriction".

module Morley.Client.RPC.Aeson
  ( morleyClientAesonOptions
  , ClientJSON(..)
  ) where

import Data.Aeson qualified as JSON
import Data.Aeson.Casing (aesonPrefix, snakeCase)
import GHC.Generics (Rep)

-- | We use these @Options@ to produce JSON encoding in the format
-- that RPC expects. We are not using defaults from @morley@ because
-- we need a specific format.
morleyClientAesonOptions :: JSON.Options
morleyClientAesonOptions = aesonPrefix snakeCase

newtype ClientJSON a = ClientJSON { unClientJSON :: a }

instance (Generic a, JSON.GToJSON JSON.Zero (Rep a), JSON.GToEncoding JSON.Zero (Rep a))
  => JSON.ToJSON (ClientJSON a) where
  toJSON = JSON.genericToJSON morleyClientAesonOptions . unClientJSON
  toEncoding = JSON.genericToEncoding morleyClientAesonOptions . unClientJSON

instance (Generic a, JSON.GFromJSON JSON.Zero (Rep a)) => JSON.FromJSON (ClientJSON a) where
  parseJSON = fmap ClientJSON . JSON.genericParseJSON morleyClientAesonOptions