Search code examples
javascriptgraphqlapollo-server

Call GraphQL mutation from another mutation


I have a GraphQL mutation that adds a book. I want to check if the author given exists yet and if not, add that author with a different mutation. Is this possible?

Mutation: {
    addAuthor: (root, args) => {
      const author = { ...args, id: uuid() }
      authors = authors.concat(author)
      return author
    },
    addBook: (root, args) => {
      const existingAuthor = authors.filter(author => author.name === args.author).length > 0
      if (!existingAuthor) {
        addAuthor({ name: args.author }) /// This is how I want to call a mutation within my mutation
      }

      const book = { ...args, id: uuid() }
      books = books.concat(book)
      return book
    }
  }

Right now, this approach throws an error from the Apollo Studio Explorer:

"path": [
        "addBook"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "ReferenceError: addAuthor is not defined"

Solution

  • Factor out your addAuthor function and use it in both places:

    Mutation: {
      addAuthor: _addAuthor,
      addBook: (_, args) => {
        const existingAuthor = authors.findIndex((a) => a.name === args.author) > -1;
        if (!existingAuthor) _addAuthor(null,{ name: args.author });
        const book = { ...args, id: uuid() }
        books = books.concat(book)
        return book
      }
    }
    
    const _addAuthor = (_, args) => {
      const author = { ...args, id: uuid() }
      authors = authors.concat(author)
      return author
    }