Created
September 7, 2024 17:42
-
-
Save acro5piano/61ee18cdecc9dae05311c82b13f994f2 to your computer and use it in GitHub Desktop.
Generate all GraphQL mutations from GraphQL schema IDL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs' | |
const header = ` | |
# | |
# This file is auto generated. Do not edit by hand. | |
# | |
`.trimStart() | |
const schema = fs.readFileSync('path/to/schema.graphql', 'utf8') | |
const allMutations = generateAllMutations(schema).join('\n') | |
fs.writeFileSync('path/to/mutations.graphql', header + allMutations, 'utf8') | |
/** @param {string} schema */ | |
function generateAllMutations(schema) { | |
schema = schema.replace(/[\s\S]+type Mutation/, '') | |
// Regex to extract all mutation fields from the schema | |
const mutationsRegex = /(\w+)\(([^)]*)\): (.+)/g | |
let match | |
const mutations = [] | |
// Loop through all matches in the schema | |
while ((match = mutationsRegex.exec(schema)) !== null) { | |
const fieldName = match[1] | |
const operationName = fieldName[0].toUpperCase() + fieldName.slice(1) | |
const argsString = match[2].trim() // Argument list as string | |
// Split the arguments string and create a key-value pair for each argument | |
const args = argsString.split(',').reduce((acc, arg) => { | |
const [argName, argType] = arg.split(':').map((s) => s.trim()) | |
acc[argName] = argType | |
return acc | |
}, {}) | |
// Generate the GraphQL variable definitions | |
const variables = Object.entries(args) | |
.map(([arg, type]) => `$${arg}: ${type}`) | |
.join(', ') | |
// Generate the mutation input arguments | |
const mutationInput = Object.keys(args) | |
.map((arg) => `${arg}: $${arg}`) | |
.join(', ') | |
// Create the mutation string with hardcoded return field 'id' | |
const mutation = ` | |
mutation ${operationName}(${variables}) { | |
${fieldName}(${mutationInput}) { | |
id | |
} | |
}` | |
mutations.push(mutation) | |
} | |
return mutations | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example output | |
# | |
# This file is auto generated. Do not edit by hand. | |
# | |
mutation CreateStore($storeName: String!) { | |
createStore(storeName: $storeName) { | |
id | |
} | |
} | |
mutation CreateStaff($storeId: ID!, $input: StaffInput!) { | |
createStaff(storeId: $storeId, input: $input) { | |
id | |
} | |
} | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment