{-# LANGUAGE OverloadedStrings #-} module Language.GraphQL.Serialize ( JSON(..) ) where import qualified Data.Aeson as Aeson import qualified Data.Aeson.Key as Aeson.Key import Language.GraphQL.Execute.Coerce import qualified Language.GraphQL.Execute.OrderedMap as OrderedMap import qualified Language.GraphQL.Type.Out as Out import qualified Language.GraphQL.Type as Type newtype JSON = JSON Aeson.Value instance Aeson.ToJSON JSON where toJSON (JSON value) = value instance Aeson.FromJSON JSON where parseJSON = pure . JSON instance Serialize JSON where serialize (Out.ScalarBaseType scalarType) value | Type.ScalarType "Int" _ <- scalarType , Int int <- value = Just $ JSON $ Aeson.Number $ fromIntegral int | Type.ScalarType "Float" _ <- scalarType , Float float <- value = Just $ JSON $ Aeson.toJSON float | Type.ScalarType "String" _ <- scalarType , String string <- value = Just $ JSON $ Aeson.String string | Type.ScalarType "ID" _ <- scalarType , String string <- value = Just $ JSON $ Aeson.String string | Type.ScalarType "Boolean" _ <- scalarType , Boolean boolean <- value = Just $ JSON $ Aeson.Bool boolean serialize _ (Enum enum) = Just $ JSON $ Aeson.String enum serialize _ (List list) = Just $ JSON $ Aeson.toJSON list serialize _ (Object object) = Just $ JSON $ Aeson.object $ toJSONKeyValue <$> OrderedMap.toList object where toJSONKeyValue (key, value) = (Aeson.Key.fromText key, Aeson.toJSON value) serialize _ _ = Nothing null = JSON Aeson.Null