Skip to content

Commit d7ad2a5

Browse files
authored
Add option to send parameters in gql-cli (#139)
1 parent 1b557a1 commit d7ad2a5

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

scripts/gql-cli

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,48 @@ from gql.transport.aiohttp import AIOHTTPTransport
66
from yarl import URL
77
import asyncio
88
import argparse
9+
import sys
10+
import json
911

1012
parser = argparse.ArgumentParser(
1113
description="Send GraphQL queries from command line using http(s) or websockets"
1214
)
1315
parser.add_argument(
1416
"server", help="the server url starting with http://, https://, ws:// or wss://"
1517
)
18+
parser.add_argument(
19+
"-p", "--params", nargs="*", help="query parameters in the form param:json_value"
20+
)
1621
args = parser.parse_args()
1722

1823

1924
async def main():
2025

26+
# Parse the params argument
27+
params = {}
28+
if args.params is not None:
29+
for p in args.params:
30+
31+
try:
32+
# Split only the first colon (throw a ValueError if no colon is present)
33+
param_key, param_json_value = p.split(':', 1)
34+
35+
# Extract the json value, trying with double quotes if it does not work
36+
try:
37+
param_value = json.loads(param_json_value)
38+
except json.JSONDecodeError:
39+
try:
40+
param_value = json.loads(f'"{param_json_value}"')
41+
except json.JSONDecodeError:
42+
raise ValueError
43+
44+
# Save the value in the params dict
45+
params[param_key] = param_value
46+
47+
except ValueError:
48+
print (f"Invalid parameter: {p}", file=sys.stderr)
49+
return 1
50+
2151
url = URL(args.server)
2252

2353
scheme = url.scheme
@@ -40,11 +70,10 @@ async def main():
4070
query = gql(query_str)
4171

4272
if scheme in ["ws", "wss"]:
43-
async for result in session.subscribe(query):
73+
async for result in session.subscribe(query, variable_values=params):
4474
print(result)
4575
else:
46-
result = await session.execute(query)
76+
result = await session.execute(query, variable_values=params)
4777
print(result)
4878

49-
5079
asyncio.run(main())

0 commit comments

Comments
 (0)