Make GraphQL query or mutation arguments a bit more DRY

37 views Asked by At

Using React and Apollo I have a mutation like this:

    const UPDATE_USER = gql`
        mutation UpdateUser($id: ID!, $someValue: String!, $someOtherValue: String!) {
            updateUser(id: $id, someValue: $someValue, someOtherValue: $someOtherValue) {
                id
                name
            }
        }
    `;

    const [mutateUser] = useMutation(UPDATE_USER, {
        variables: { id: 123, someValue: 'Hello', someOtherValue: 'World' },
    });

Works perfectly but the UpdateUser mutation is now just passing on arguments which doesn't seem very DRY to me. I'm wondering if there is a way to shorten the code or make it a bit more manageable so that when another argument is added for example I don't have to retype it 4 times.

1

There are 1 answers

1
SlothOverlord On

If you have access to the api, you can define it a little bit different:

const UPDATE_USER = gql`
    mutation UpdateUser($data: UpdateUserInput!) {
        updateUser(data: $UpdateUserInput) {
            id
            name
        }
    }
`;

const [mutateUser] = useMutation(UPDATE_USER, {
    variables: { data: { id: 123, someValue: 'Hello', someOtherValue: 'World' }},
});

Then in your api:

//User.type.js
//Note that this code depends on how you integrated your graphql solution. But the logic is here

const UpdateUserInputType = new GraphQLInputObjectType({
  name: "UpdateUserInput",
  fields: () => ({
    id: { type: new GraphQLNonNull(GraphQLID) },
    someValue: { type: new GraphQLNonNull(GraphQLString) },
    SomeOtherValue: { type: GraphQLString },
  }),
});

And then add UpdateUserInputType to your data arg at your resolver