繁体   English   中英

在 Graphql 中设置参数可选

[英]Set argument optional in Graphql

在我的 mongodb model 中,名称是必需的,但我想在 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) )
                })
            }
        }

您正在滥用findByIdAndUpdate function。 它可能应该以这种方式使用:

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 版本,您可以使用更新的?? 运算符而不是|| .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM