Skip to content

Instantly share code, notes, and snippets.

@lprhodes
Last active March 11, 2024 10:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lprhodes/312cb8dbea53d233a1a1 to your computer and use it in GitHub Desktop.
Save lprhodes/312cb8dbea53d233a1a1 to your computer and use it in GitHub Desktop.
GraphQL JS (ES6): Convert GraphQLObjectType to GraphQLInputObjectType
// 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