Martini Defining GraphQL Queries & Mutations
Inputs
When defining GraphQL operations in Martini, your queries and mutations are represented through models. These models are designed to encapsulate the structure and requirements of your GraphQL operations, ensuring that they are executed as intended.
Model Representation
Your query or mutation is encapsulated in a model that mirrors the structure and parameters of the GraphQL operation. This model consists of two main components: args
and output
.
-
Model Naming: The name of the model must directly correspond to the name of the query or mutation type you are invoking. For instance, if your query is named
get_product
, the model should also be namedget_product
. -
Args (Arguments): This section represents the arguments required by your GraphQL operation. It is structured as a map of key-value pairs, where each key corresponds to an argument name, and the value represents the argument's value.
-
Output: This section defines the expected structure of the data returned by the query or mutation. It allows you to specify which fields should be included in the response.
Query Example
For a get_product
query, you might structure your model as follows:
1 2 3 4 5 |
|
To fetch a specific product, you would populate the args
with the corresponding product_id
. The output
would define the structure of the product information you wish to retrieve.
Mutation Example
For a mutation, such as create_product
, the model would similarly define args
for input data and output
for the mutation result:
1 2 3 4 5 |
|
Here, the args
would contain the new product's details, and the output
would typically be a boolean indicating the operation's success.
Direct String Queries and Mutations
In scenarios where you prefer or require direct string representation of your GraphQL operations, Martini supports executing queries and mutations defined as plain strings. This method involves creating a JSON object where the query or mutation string is assigned to a parameter named query
.
Sample Formats
-
Query:
{ get_contact { _id name age } }
{ get_contact ( _id: “1000” ) { _id name age } }
-
Mutation:
mutation { create_contact( name: "John Doe" age: 10 ) }
mutation { update_contact( _id: "12345" age: 12 ) }
mutation { delete_contact( _id: "12345" ) }
This approach offers flexibility for dynamically constructed queries or mutations and can be particularly useful in complex scenarios or when integrating with existing codebases.