Search code examples
graphqlgraphql-js

Object mutations in graphQL


Here is my EventAttendee Object.

const EventAttendee = new GraphQLInputObjectType({
  name: 'EventAttendee',
  fields: () => ({
    attendeeName: {type: GraphQLString},
    personalizedDateSelection: {type: new GraphQLInputObjectType()}
  })
});

The personalizedDateSelection property is an dynamic one and its properties are not known now. So, In this case, I have given GraphQLInputObjectType().

But it gives an error stating EventAttendee.personalizedDateSelection field type must be Output Type.

How to define an ObjectType whose properties are not known ?


Solution

  • I wanted personalizedDateSelection property of EventAttendee to be of objectType but I dont know those properties in advance, but I am sure that it is of Object type.

    So declaring this as GraphQLScalarType was the correct way to do it. Check out about GraphQLScalarType. But we need to create a custom scalar type. All scalar types can be of input type. So here is my implementation:

    const PersonalizedDateSelection = new GraphQLScalarType({
        name: 'PersonalizedDateSelection',
        serialize: value => {
          return value;
        },
        parseValue: value => {
          return value;
        },
        parseLiteral: ast => {
          console.log("coming in parseLiteral");
          console.log(ast);
          let value = {};
          if (ast.kind !== Kind.OBJECT) {
            throw new GraphQLError("Query error: Can only parse object but got a: " + ast.kind, [ast]);
          }
          ast.fields.forEach(field => {
            value[field.name.value] = parseJSONLiteral(field.value);
          });
    
          return value;
        }
    });