{-|
Module      : Dialogflow.Util
Description : Utilities
Copyright   : (c) Mauricio Fierro, 2019
License     : BSD3-Clause
Maintainer  : Mauricio Fierro <mauriciofierrom@gmail.com>

This module contains misc utility functions.
-}

module Dialogflow.Util
  ( toObject
  , noNullObjects
  ) where

import Data.Aeson ( ToJSON
                  , toJSON
                  , object
                  , Value(..)
                  , Object )
import Data.Aeson.Types (Pair)

-- | Turn a value into an aeson @Object@
toObject :: ToJSON a => a -> Object
toObject :: a -> Object
toObject a
a = case a -> Value
forall a. ToJSON a => a -> Value
toJSON a
a of
  Object Object
o -> Object
o
  Value
_        -> [Char] -> Object
forall a. HasCallStack => [Char] -> a
error [Char]
"toObject: value isn't an Object"

{-|
   Removes values that were parsed to @Null@ values.
   Useful to avoid having @null@ values in generated
   JSON for @Nothing@ values.
-}
noNullObjects :: [Pair] -> Value
noNullObjects :: [Pair] -> Value
noNullObjects = [Pair] -> Value
object ([Pair] -> Value) -> ([Pair] -> [Pair]) -> [Pair] -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Pair -> Bool) -> [Pair] -> [Pair]
forall a. (a -> Bool) -> [a] -> [a]
filter (\(Text
_,Value
v) -> Value
v Value -> Value -> Bool
forall a. Eq a => a -> a -> Bool
/= Value
Null)