I recommend storing the graphql in one file, and script for processing it in a separate file, and then combining the two at the prompt.
This lets you use graphql syntax highlighting plugins and graphql pretty printers while editing examplequery.gql
in your favorite editor. While also preserving the ability to make use of your cli toolkit for cases where your graphql-fu isn't up to the task.
Usage:
❯ ./ghgql.sh examplequery.gql
{"data":{"user":{"repositories":{"nodes":[{"name":"firstrepo","languages":{"nodes":[]}},{"name":"secondrepo","languages":{"nodes":[{"name":"Shell"},{"name":"Vim script"}]}},{"name":"thirdrepo","languages":{"nodes":[{"name":"TeX"}]}}]}}}}
❯ ./ghgql.sh examplequery.gql \
| jq -c '.data.user.repositories.nodes | to_entries | .[]' \
| grep 'TeX' \
| jq -r '.value.name'
thirdrepo
ghgql.sh
#!/usr/bin/env bash
if [ ! -f $1 ] || [ $# -ne 1 ]
then
echo Queries the github graphql API
echo "Usage:"
echo
echo "$0 somefile.gql"
fi
# read the gql query from the file named in the argument
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
TOKEN=$(cat $DIR/token)
QUERY=$(jq -n \
--arg q "$(cat $1 | tr -d '\n')" \
'{ query: $q }')
# do the query
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Authorization: bearer $TOKEN" \
--data "$QUERY" \
https://api.github.com/graphql
examplequery.gql
{
user(login: "MatrixManAtYrService") {
repositories(first: 3) {
nodes {
name
languages(first: 3) {
nodes {
name
}
}
}
}
}
}