【问题标题】:How to set argument optional in Graphql?如何在 Graphql 中设置可选参数?
【发布时间】:2020-08-25 16:25:24
【问题描述】:

在我的 mongodb 模型中,名称是必需的,但我想在 graphql 中将其设为可选。我该怎么做?

    updateExercise: {
            type: ExerciseType,
            args: {
                id: {type: new GraphQLNonNull(GraphQLString)},
                username: {type: new GraphQLString},
                description: {type: new GraphQLString},
                duration: {type: new GraphQLInt},
                date: {type: new GraphQLString}
            },
            resolve(parent, args) {
                Exercise.findByIdAndUpdate(args.id)
                .then(exercise => {
                    exercise.username = args.username,
                    exercise.description = args.description,
                    exercise.duration = args.duration,
                    exercise.date = args.date
                    exercise.save()
                    .then( () => 'Succesfully Updated')
                    .catch( e => console.log(e) )
                })
            }
        }

【问题讨论】:

    标签: graphql graphql-js


    【解决方案1】:

    您误用了findByIdAndUpdate 函数。大概应该这样使用:

    const SomeType = new GraphQLObjectType({
        updateExercise: {
                type: ExerciseType,
                args: {
                    id: {type: new GraphQLNonNull(GraphQLString)},
                    username: {type: GraphQLString},
                    description: {type: GraphQLString},
                    duration: {type: GraphQLInt},
                    date: {type: GraphQLString}
                },
                resolve(parent, args) {
                    return Exercise.findByIdAndUpdate(args.id, {
                        username: args.username || undefined,
                        description: args.description,
                        duration: args.duration,
                        date: args.date
                    }).then(() => 'Succesfully Updated')
                      .catch(e => console.log(e))
                })
            }
        }
    });
    

    我们在 JS 中使用了一个小技巧来短路返回值。当args.usernamenull 时,这将为用户名属性提供undefined。如果您处于不确定 undefined 是否已重新分配的环境中,则可以改用 void 0。如果您使用的是新的 TypeScript 或 EcmaScript 版本,则可以使用较新的 ?? 运算符而不是 ||

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 1970-01-01
      • 2019-04-10
      • 2021-12-22
      • 2010-11-14
      • 2023-04-06
      • 1970-01-01
      • 2021-02-02
      • 2020-01-02
      相关资源
      最近更新 更多