在GraphQL中进行突变之前删除只读字段 [英] Remove read-only fields before mutation in GraphQL

查看:17
本文介绍了在GraphQL中进行突变之前删除只读字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的架构中有一个名为Article的类型:

type Article {
  id: ID!
  updated: DateTime
  headline: String
  subline: String
}

对于它的更新,updateArticle(id: ID!, article: ArticleInput!)突变使用了相应的输入类型:

input ArticleInput {
  headline: String
  subline: String
}

突变本身如下所示:

mutation updateArticle($id: ID!, $article: ArticleInput!) {
  updateArticle(id: $id, article: $article) {
    id
    updated
    headline
    subline
  }
}
文章始终保存为一个整体(而不是单个字段逐个保存),因此当我将文章传递给前面获取的突变时,它会抛出错误,如Unknown field. In field "updated"Unknown field. In field "__typename"Unknown field. In field "id"。这些问题的根本原因是这些字段没有在输入类型上定义。

根据spec

,这是正确的行为

(…)此无序映射不应包含名称未包含的任何条目 由此输入对象类型的字段定义,否则为错误 应引发。

现在我的问题是,处理这种情况的好方法是什么。我是否应该在应用代码中列出输入类型允许的所有属性?

如果可能的话,我想避免这种情况,也许可以让一个实用程序函数为我切掉它们,因为它知道输入类型。但是,因为客户端不知道模式,所以这必须发生在服务器端。因此,不必要的属性会转移到那里,我想这就是为什么它们一开始就不应该转移的原因。

是否有比维护属性列表更好的方法?

我使用的是apollo-clientreact-apollographql-server-express

推荐答案

您可以对查询使用片段,其中包括数据的所有可变字段。filter utility可以使用该片段在突变发生之前删除所有不需要的数据。

要点是:

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 filterGraphQlFragment from 'graphql-filter-fragment';

...

graphql(articleUpdateMutation, {
  props: ({mutate}) => ({
    onArticleUpdate: (id, article) =>
      // Filter for properties the input type knows about
      mutate({variables: {id, article: filterGraphQlFragment(ArticleMutableFragment, article)}})
  })
})

...

ArticleMutable片段现在还可以用于创建新项目。

这篇关于在GraphQL中进行突变之前删除只读字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆