Exploring the Depths of GraphQL Mutations: Nesting for

Currently seeking examples of writing nested mutations. Specifically, I am creating a mutation for a recipe object with the following schema:

const RecipeType = new GraphQLObjectType({
  name: "Recipe",
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    dateCreated: { type: GraphQLString },
    authorID: { type: GraphQLID },
    prepTime: { type: PrepTimeType },
    cookTime: { type: CookTimeType },
    ingredients: { type: new GraphQLList(IngredientType) },
    steps: { type: new GraphQLList(StepType) }
  })
});

const PrepTimeType = new GraphQLObjectType({
  name: "PrepTime",
  fields: () => ({
    quantity: { type: GraphQLFloat },
    unit: { type: GraphQLString }
  })
});

const CookTimeType = new GraphQLObjectType({
  name: "CookTime",
  fields: () => ({
    quantity: { type: GraphQLFloat },
    unit: { type: GraphQLString }
  })
});

const IngredientType = new GraphQLObjectType({
  name: "Ingredients",
  fields: () => ({
    name: { type: GraphQLString },
    quantity: { type: GraphQLFloat },
    unit: { type: GraphQLString }
  })
});

const StepType = new GraphQLObjectType({
  name: "Ingredients",
  fields: () => ({
    details: { type: GraphQLString },
    estimatedTime: { type: GraphQLFloat },
    unit: { type: GraphQLString }
  })
});

In order to create an entire object for this item, I need to write a mutation like the one below:

createRecipe: {
  type: RecipeType,
  args: {
    // Required Args
    name: { type: new GraphQLNonNull(GraphQLString) },
    authorID: { type: new GraphQLNonNull(GraphQLID) },
    ingredients: { type: new GraphQLList(IngredientType) },
    steps: { type: new GraphQLList(StepType) },
    // Not required args
    prepTime: { type: PrepTimeType },
    cookTime: { type: CookTimeType },
  },
  resolve(parent, args) {
    let recipe = new Recipe({
      name: args.name,
      dateCreated: new Date().getTime(),
      authorID: args.authorID,
      ingredients: args.ingredients,
      steps: args.steps
    });

    // Handle optional arguments
    args.prepTime ? recipe.prepTime = args.prepTime : recipe.prepTime = null;
    args.cookTime ? recipe.cookTime = args.cookTime : recipe.cookTime = null;

    return recipe.save();
  }
}

Struggling with creating a single mutation that handles the complete object creation, and updating will be an additional challenge. Any guidance, examples, or documentation links would be helpful as it seems GraphQL lacks clear instructions on this topic.

Encountering the following errors currently:

{
  "errors": [
    {
      "message": "The type of Mutation.createRecipe(ingredients:) must be Input Type but got: [Ingredients]."
    },
    {
      "message": "The type of Mutation.createRecipe(steps:) must be Input Type but got: [Steps]."
    },
    {
      "message": "The type of Mutation.createRecipe(prepTime:) must be Input Type but got: PrepTime."
    },
    {
      "message": "The type of Mutation.createRecipe(cookTime:) must be Input Type but got: CookTime."
    }
  ]
}

Appreciate any assistance provided.

Thanks,

Answer №1

After some exploration, I successfully tackled this issue by creating input types for each subdocument. While I already had the object types in place, I realized that I needed to introduce new ones for the mutations. Subsequently, I integrated them into the mutation as outlined below.

createRecipe: {
  type: RecipeType,
  args: {
    // Necessary Arguments
    name: { type: new GraphQLNonNull(GraphQLString) },
    authorID: { type: new GraphQLNonNull(GraphQLID) },
    ingredients: { type: new GraphQLList(IngredientInputType) },
    steps: { type: new GraphQLList(StepInputType) },
    // Optional Arguments
    prepTime: { type: PrepTimeInputType },
    cookTime: { type: CookTimeInputType },
  },
  resolve(parent, args) {
    let recipe = new Recipe({
      name: args.name,
      dateCreated: new Date().getTime(),
      authorID: args.authorID,
      ingredients: args.ingredients,
      steps: args.steps
    });

    // Handling optional arguments and assigning to recipe if present
    args.prepTime ? recipe.prepTime = args.prepTime : recipe.prepTime = null ;
    args.cookTime ? recipe.cookTime = args.cookTime : recipe.cookTime = null ;

    return recipe.save();
  }
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing two values when an option is selected in a dropdown in Javascript using the map functionIn this tutorial,

The JSON data provided is structured as follows: [ { "course_name": "React", "course_id": 2 }, { "course_name": "Python", "course_id": 1 } ] Displa ...

Trouble with ternary operator within array .find() method in JavaScript

I came across a puzzling scenario while using a ternary operator within the .find method of an array. In my search for an object: Consider this: const list = [ { id: 1, name: "dave"}, { id: 3, name: "choi"}, {id: 4, name: "bob"} ] // this work ...

What is the process of setting up a clustered index in MongoDB with the .NET driver?

I'm having trouble figuring out how to set up a clustered index in MongoDB using the .NET driver. Despite my efforts with reading documentation and exploring methods like Collection.Indexes.CreateOneAsync and Database.CreateCollection, I haven't ...

Can the ng-keypress listen for arrow key presses?

I'm looking to implement a functionality similar to the konami code "up, up, down, down, a, b, a, b, enter" -> triggering an action. Is it feasible to detect arrow key presses using ng-keypress in AngularJS? It doesn't seem to be working as e ...

Guide to populating a full calendar using JSON information

Implementing the FUllCALENDAR CSS template for creating a meeting calendar has been my current project. The servlet class I am using is CalendarController. However, when running it, the output appears as follows: {"events":[{"id":1,"title":"1","s ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

Notifying when a refreshed PHP interactive clock has detected new input

I have created a simple countdown timer in PHP that will continuously update the result to be displayed on the page using JavaScript. I am still deciding whether updating every second could potentially cause any issues. The way the countdown works is by r ...

Experiencing issues with recognizing HTML DOM functions during Jest testing

I encountered an issue that reads as follows: TypeError: document.querySelector is not a function This error occurred in the line below: selectElement = document.querySelector('#selectbox'); The purpose of this line is to retrieve the selec ...

Fetching Data from DataTable using AJAX in Codeigniter

I am currently developing an application using CodeIgniter. Below is the code: Controller: public function index(){ $data = array( 'record' => $this->Parameter_model->get_parameter('tbl_parameter') ); ...

What strategies can I implement to enhance the efficiency of my search suggestions?

I recently implemented a search suggestion feature on my website similar to Google Suggest, but I've noticed that the speed is a bit sluggish... Here's how I set it up: When a user starts typing in the search bar, I use Ajax to send the keyword t ...

Experiencing problems with geolocation feature policy while working with Ionic framework

Currently, I have integrated Google maps into my Ionic project using the code snippet below: this.geolocation.getCurrentPosition().then((position) => { let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); let ...

During the AJAX request on the HTML page, additional elements are being added

I've implemented a piece of code that utilizes AJAX calls to refresh an HTML table every 5 seconds. The approach involves clearing out the content of the table and then appending all data once again every 10 seconds. Here's a snippet of the code ...

Having trouble with creating SQLite tables using JavaScript within a for loop

I have developed a multi-platform app using AngularJS, JavaScript, Phonegap/Cordova, Monaca, and Onsen UI. In order to enable offline usage of the app, I have integrated an SQLite Database to store various data. After conducting some basic tests, I confir ...

A more efficient method for creating node.js functions to read and write files

Is there a more efficient way to optimize this code? var fs = require('fs'); var file = '/test.txt'; fs.readFile(file, 'utf8', function (err, txt) { if (err) return console.log(err); txt = txt + '\nApp ...

angular.js causing json data not being interpreted correctly as rows

Struggling with setting up an angular.js page to display data fetched through a http get request from a node.js server. Encountering issues with how angular is parsing the json data. Below is the index.html code snippet: <!DOCTYPE html> <html > ...

Increase the width of the div to extend it to the right side of the

After analyzing the issue, it seems like the solution lies in extending the wrapper div to the right side of the page without any wrapping. Whenever I attempt to set the width to 100vw or 100%, the content within the div gets pushed below all the other ele ...

combining all JavaScript script tags into a single tag

I'm currently working with wavesurfer.js and have the following setup: 'use strict' <!-- wavesurfer.js --> <script src="src/wavesurfer.js"></script> <script src="src/util.js"></script> <scrip ...

Challenge of Combining ACE Editor with Keystone.js Application

According to this source (), all you need to do is copy one of the src* subdirectories into your project. In my case, I placed it in mykeystoneapp/public/js (my default home is mykeystoneapp/public). However, I am encountering the following errors: 1. Un ...

The object failed to be transferred to another function in React

I am currently learning React and following a video tutorial. I have encountered an issue where an object cannot be passed to another method, but it works fine when I pass an ID instead. Here is the method: handleIncrement = (product) => { console. ...

WindowWizard - Unlocks the ability to open two windows simultaneously with just one click

Every time I click on the button below, it seems to open the page twice. I'm having trouble identifying the issue: The code in the .cs file: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { btnPrint. ...