defmodule Arland.RabbitMQ.Helper do def ping() do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "ping" }} ) |> validate_response() end # DataBase operations def create_database(database_name) do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "create_database", "params" => %{ "database_name" => database_name } }} ) |> validate_response() end def delete_database(database_name) do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "delete_database", "params" => %{ "database_name" => database_name } }} ) |> validate_response() end def list_databases() do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "list_databases" }} ) |> validate_response() end # Document operations def create_document(database_name, document_id, document) do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "create_document", "params" => %{ "database_name" => database_name, "document_id" => document_id, "document" => document } }} ) |> validate_response() end def read_document(database_name, document_id) do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "read_document", "params" => %{ "database_name" => database_name, "document_id" => document_id } }} ) |> validate_response() end def update_document(database_name, document_id, document) do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "update_document", "params" => %{ "database_name" => database_name, "document_id" => document_id, "document" => document } }} ) |> validate_response() end def delete_document(database_name, document_id) do GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "delete_document", "params" => %{ "database_name" => database_name, "document_id" => document_id } }} ) |> validate_response() end def list_documents(database_name, selector) do {:ok, response} = GenServer.call( Arland.RabbitMQ.Gramnad, {:rpc, %{ "action" => "list_documents", "params" => %{ "database_name" => database_name, "selector" => selector } }} ) |> validate_response() {:ok, Map.get(response, "docs")} end defp validate_response(response) do decoded_response = Jason.decode!(response) cond do is_list(decoded_response) -> {:ok, decoded_response} true -> has_ok = Map.has_key?(decoded_response, "ok") has_status = Map.has_key?(decoded_response, "status") has_error = Map.has_key?(decoded_response, "error") if has_ok or has_status do {:ok, decoded_response} end if has_error do {:error, decoded_response} end {:ok, decoded_response} end end end