简体   繁体   中英

GraphQL Mongoose promise best practices

Using GraphiQL, I'm able to update a user with the following command (1). I'm able to return the actual user with the service (3).

Is there simpler/more compact way of returning the user after an update? (seen how easy it is when creating a user).

(1) GraphiQL mutation command mutation { updateUser(id: "1", firstName: "Bob"){ firstName } }

(2) the mutation:

const mutation = new GraphQLObjectType({
updateUser: {
  type: UserType,
  args: {
    id:         { type: new GraphQLNonNull(GraphQLString) },
    firstName:  { type: GraphQLString },
    age:        { type: GraphQLInt },
    companyId:  { type: GraphQLString }
  },
  resolve(parentValue, args){
    return UserService.updateUser(args);
  }
},
})

(3) the service:

function updateUser(args) {
  var {id} = args;
  return User.findOne({id})
    .then(user => {
      if(!user){throw new Error('No user found')}
      return User.update({id}, args)
         .then(() => {
           return User.findOne({id})
         })
    })
},
function addUser(args) {
  const user = new User(args);
  return user.save(args);
}

Assuming you're using mongoose :

function updateUser(args) {
  var {id} = args;

  return await User.findOneAndUpdate({ id }, args, { new: true });
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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