首页 文章

使用GraphQL中的必填字段更新突变

提问于
浏览
0

我想使用相同的变异来添加和更新graphQL中的资源 .

问题是如果我设置了必填字段,我需要在每次想要更新资源时设置所有字段 .

例:

const mutation = {
    user: {
        type: UserType,
        args: {
            id: {
                type: GraphQLString
            },
            userName: {
                type: GraphQLNonNull(GraphQLString)
            },
            name: {
                type: GraphQLString
            },
            password: {
                type: GraphQLNonNull(GraphQLString)
            },
            password_confirmation: {
                type: GraphQLNonNull(GraphQLString)
            }
        },
        resolve: (obj, input) => {
            if (input.id !== undefined) {
                updateUser(input.id, input)
            } else {
                addUser(input)
            }
        }
    }
}

在这种情况下,如果我想更新用户名,我还要再次设置用户名,密码和password_confirmation .

1 回答

  • 0

    您可以从输入中删除 GraphQLNonNull 包装并自行检查真实性,但前提是您正在创建用户 . 一个简单的例子:

    if (input.id) {
      updateUser(input.id, input)
    } else {
      const fields = ['userName', 'password', 'password_confirmation', 'name']
      fields.forEach(field => {
        if (!(field in input)) throw new Error(`Missing ${field} in input`)
      })
      addUser(input)
    }
    

相关问题