module Database.Neo4j.Cypher (
Response(..), ParamValue(..), Params, newparam,
cypher, fromResult, fromSuccess, isSuccess
) where
import Data.Aeson ((.=), (.:))
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import qualified Data.Aeson as J
import qualified Data.ByteString as S
import qualified Data.HashMap.Lazy as M
import qualified Data.Text as T
import Database.Neo4j.Types
import Database.Neo4j.Http
data Response = Response {cols :: [T.Text], vals :: [[J.Value]]} deriving (Show, Eq)
instance J.FromJSON Response where
parseJSON (J.Object o) = Response <$> (o .: "columns" >>= J.parseJSON) <*> (o .: "data" >>= J.parseJSON)
parseJSON _ = mzero
cypherAPI :: S.ByteString
cypherAPI = "/db/data/cypher"
data ParamValue = ParamLiteral PropertyValue | ParamProperties Properties | ParamPropertiesArray [Properties]
deriving (Show, Eq)
newparam :: PropertyValueConstructor a => a -> ParamValue
newparam = ParamLiteral . newval
instance J.ToJSON ParamValue where
toJSON (ParamLiteral l) = J.toJSON l
toJSON (ParamProperties p) = J.toJSON p
toJSON (ParamPropertiesArray ps) = J.toJSON ps
type Params = M.HashMap T.Text ParamValue
cypher :: T.Text -> Params -> Neo4j (Either T.Text Response)
cypher cmd params = Neo4j $ \conn -> httpCreate4XXExplained conn cypherAPI body
where body = J.encode $ J.object ["query" .= cmd, "params" .= J.toJSON params]
fromResult :: Response -> Either T.Text Response -> Response
fromResult def (Left _) = def
fromResult _ (Right resp) = resp
fromSuccess :: Either T.Text Response -> Response
fromSuccess (Left _) = error "Cypher.fromSuccess but is Error"
fromSuccess (Right resp) = resp
isSuccess :: Either T.Text Response -> Bool
isSuccess (Left _) = False
isSuccess (Right _) = True