1

In GraphQL, I have two types, Author and Quotes, as follow:

  type Author {
    id: Int!
    name: String!
    last_name: String!
    quotes: [Quote!]!
  }

  type Quote {
    id: Int!
    author: Author! 
    quote: String!
  } 

In the implementation an Author and a Quote could be created individually.
But I want to add the functionality to create the author and multiple quotes in the same request as follows:

mutation{
  createAuthor(author:{
    name:"Kent",
    last_name:"Beck",
    quotes:[
      {
        quote: "I'm not a great programmer; I'm just a good programmer with great habits."
      },
      {
        quote: "Do The Simplest Thing That Could Possibly Work"
      }
    ]
  }) {
    id
    name
    quotes{ 
      quote
    }
  }
} 

If the client want to merge the creation as shown above, what is the most perfect way of doing it?

The current implementation for author creation with multiple quotes is as follow:

resolve (source, args) {
    return models.author.build({
        name: args.author.name,
        last_name: args.author.last_name
    }).save().then(function(newAuthor) {
        const quotes = args.author.quotes || [];
        quotes.forEach((quote) => {
          models.quote.create({
            author_id: newAuthor.id,
            quote: quote.quote,
          });
        });

        return models.author.findById(newAuthor.id);
    });
}

Can I somehow invoke the Quotes creation mutations automatically?

CoderX
  • 942
  • 1
  • 10
  • 30

0 Answers0