Skip to content

Commit

Permalink
Merge pull request #2 from Snedashkovsky/add_graphql
Browse files Browse the repository at this point in the history
Add parameters for GraphQL execution
  • Loading branch information
Snedashkovsky authored May 11, 2023
2 parents 4ea761e + c9c2e4e commit 7fad59c
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 3 deletions.
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,46 @@ res = await execute_graphql(
graphql_url='https://index.bostrom.cybernode.ai/v1/graphql')

pd.DataFrame(res['contracts'])
```
a query with variable values
```python
import pandas as pd

from cyberutils.graphql import execute_graphql

res = await execute_graphql(
request="""
query ContractsCodeID($code_id: bigint) {
contracts(order_by: {tx: desc_nulls_last}, where: {code_id: {_eq: $code_id}}) {
address
admin
creation_time
creator
fees
gas
height
label
tx
code_id
}
}
""",
variable_values={"code_id": "3"},
graphql_url='https://index.bostrom.cybernode.ai/v1/graphql')

pd.DataFrame(res['contracts'])
```
get messages with a given address and type
```python
import pandas as pd

from cyberutils.graphql import get_messages_by_address_and_type


res = await get_messages_by_address_and_type(
address='bostrom1xszmhkfjs3s00z2nvtn7evqxw3dtus6yr8e4pw',
msg_type='cosmos.bank.v1beta1.MsgSend',
graphql_url='https://index.bostrom.cybernode.ai/v1/graphql')

pd.DataFrame(res)
```
1 change: 1 addition & 0 deletions cyberutils/graphql/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .execution import execute_graphql
from .queries import get_messages_by_address_and_type
32 changes: 30 additions & 2 deletions cyberutils/graphql/execution.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
from typing import Union, Optional, Dict, Any

from graphql import ExecutionResult
from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport


async def execute_graphql(request: str, graphql_url: str) -> dict:
async def execute_graphql(request: str,
graphql_url: str,
variable_values: Optional[Dict[str, Any]] = None,
operation_name: Optional[str] = None,
serialize_variables: Optional[bool] = None,
parse_result: Optional[bool] = None,
get_execution_result: bool = False,
**kwargs,
) -> Union[Dict[str, Any], ExecutionResult]:
"""
Execute a GraphQL query
:param request: the GraphQL request as a String
:param graphql_url: The GraphQL server URL. Example: 'https://server.com:PORT/path'.
:param variable_values: Dictionary of input parameters.
:param operation_name: Name of the operation that shall be executed.
:param serialize_variables: whether the variable values should be
serialized. Used for custom scalars and/or enums.
By default, use the serialize_variables argument of the client.
:param parse_result: Whether gql will unserialize the result.
By default, use the parse_results argument of the client.
:param get_execution_result: return the full ExecutionResult instance instead of
only the "data" field. Necessary if you want to get the "extensions" field.
:return: GraphQL result
"""
# Select your transport with a defined url endpoint
Expand All @@ -17,4 +37,12 @@ async def execute_graphql(request: str, graphql_url: str) -> dict:
) as _session:
# Execute a query
_gql_query = gql(request_string=request)
return await _session.execute(_gql_query)
return await _session.execute(
document=_gql_query,
variable_values=variable_values,
operation_name=operation_name,
serialize_variables=serialize_variables,
parse_result=parse_result,
get_execution_result=get_execution_result,
**kwargs,
)
49 changes: 49 additions & 0 deletions cyberutils/graphql/queries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from typing import Optional, Dict, List

from .execution import execute_graphql


async def get_messages_by_address_and_type(address: str,
msg_type: str,
graphql_url: str,
limit: int = 100,
offset: int = 0) -> Optional[List[Dict]]:
"""
get messages with a given address and type
:param address: network address
:param msg_type: type of message, ex. `cosmos.bank.v1beta1.MsgSend`
:param graphql_url: The GraphQL server URL. Example: 'https://server.com:PORT/path'.
:param limit: limit of entities
:param offset: where in the list the server should start when returning items for a query
:return: dict with messages
"""
_res = await execute_graphql(
request="""
query MessagesByAddressAndType($address: _text, $types: _text, $limit: bigint, $offset: bigint) {
messages_by_address(
args: {addresses: $address, limit: $limit, offset: $offset, types: $types}
order_by: {transaction: {block: {height: desc}}}
) {
message_type: type
message_value: value
message_involved_addresses: involved_accounts_addresses
transaction_hash
transaction {
success
memo
signer_infos
}
}
}
""",
variable_values={
"address": f"{{{address}}}",
"types": f"{{{msg_type}}}",
"limit": str(limit),
"offset": str(offset)
},
graphql_url=graphql_url)
try:
return _res['messages_by_address']
except KeyError:
return
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ license = "MIT"
packages = [{ include = "cyberutils" }]
readme = "README.md"
repository = "https://github.com/Snedashkovsky/cyberutils.git"
version = "0.0.2"
version = "0.0.3"

[tool.poetry.dependencies]
pandas = "^1.0.0"
Expand Down

0 comments on commit 7fad59c

Please sign in to comment.