Remove unnecessary fields before mutation in GraphQL
So the most elegant way I could think of is using a fragment for the query, which includes all mutable fields of the data. That fragment can be used by the filter utility of graphql-anywhere
to remove all unwanted data before the mutation happens.
The gist is:
const ArticleMutableFragment = gql`
fragment ArticleMutable on Article {
headline
subline
publishing {
published
time
}
}
`
const ArticleFragment = gql`
fragment Article on Article {
...ArticleMutable
id
created
updated
}
${ArticleMutableFragment}
`;
const query = gql`
query Article($id: ID!) {
article(id: $id) {
...Article
}
}
${ArticleFragment}
`;
const articleUpdateMutation = gql`
mutation updateArticle($id: ID!, $article: ArticleInput!) {
updateArticle(id: $id, article: $article) {
...Article
}
}
${ArticleFragment}
`;
...
import {filter} from 'graphql-anywhere';
...
graphql(articleUpdateMutation, {
props: ({mutate}) => ({
onArticleUpdate: (id, article) =>
// Filter for properties the input type knows about
mutate({variables: {id, article: filter(ArticleMutableFragment, article)}})
})
})
...
The ArticleMutable
fragment can now also be reused for creating new articles.