Batch GraphQL Mutations (single gql document)

JS
S
JavaScript

Idea: concatenate the strings for the separate createAuthor mutations into a single GraphQL document using GraphQL Aliases.

1const createAuthor = (name) => {
2  const alias = `alias_${Math.random().toString(36).slice(2)}`
3
4  return `
5    ${alias}: createAuthor(name: "${name}") {
6      id
7    }
8  `
9}
10
11const createAuthors = (mutations) => {
12  const joinedMutations = mutations.join('\n')
13  
14  return `
15  mutation createAuthors {
16    ${joinedMutations}
17  }
18  `
19}
20
21const mutations  = ["Edgar Allan Poe", "Arthur Conan Doyle"]
22  .map(name => createAuthor(name))
23const result = createAuthors(mutations)

Created on 6/28/2019