Last active
March 11, 2024 10:21
-
-
Save lprhodes/312cb8dbea53d233a1a1 to your computer and use it in GitHub Desktop.
GraphQL JS (ES6): Convert GraphQLObjectType to GraphQLInputObjectType
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
// GraphQL Utils | |
// Module Vars | |
import { | |
graphql, | |
GraphQLObjectType, | |
GraphQLInputObjectType, | |
GraphQLID | |
} from 'graphql'; | |
import { isInputType } from 'graphql/type/definition'; | |
export function convertToInputObjectType(input, objectType) { | |
// Create the GraphQLInputObjectType fields by itterating over the provided GraphQLObjectType's fields | |
const objectFields = objectType._typeConfig.fields(); | |
const inputObjectFields = {}; | |
for (const fieldName in objectFields) { | |
// Make sure we only include fields that the mutation requires | |
if (!input.hasOwnProperty(fieldName)) { | |
continue; | |
} | |
let field = objectFields[fieldName]; | |
const fieldType = field.type; | |
// If the field is not an Input Type, convert it to be so | |
if (!isInputType(fieldType)) { | |
const fieldInput = input[field]; | |
field.type = convertToInputObjectType(fieldInput, fieldType); | |
// Use the field only if its' converted input type was returned | |
if (field.type) { | |
inputObjectFields[fieldName] = field; | |
} | |
} else { | |
inputObjectFields[fieldName] = field; | |
} | |
} | |
// Give the input object a name | |
const inputObjectName = objectType.name + 'Input'; | |
const InputObject = new GraphQLInputObjectType({ | |
name: inputObjectName, | |
fields: inputObjectFields | |
}); | |
return InputObject; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment