mercredi 12 février 2020

What is a good pattern to use for user creation?

I have the following logic, which feels very smelly, I'm wondering if anyone encountered such code? or if someone know which is the optimal pattern(s) to follow?

const upsertAdmin = async (email, password, ownership, messages) => {
  let user = await User.findOne({email});
  if(!user) {
    if(!password) {
      messages.push('Admin was not created, password is required');
    } else {
      user = new User({
        name: email,
        email,
        password,
        permissions: [ownership],
      });
      messages.push('Admin user created');
      await user.save();
    }
  } else {
    messages.push('Admin user found');
    let shouldSave = false;
    if(password) {
      user.password = password;
      messages.push('Admin password updated');
      shouldSave = true;
    }
    if(user.permissions.indexOf(ownership) === -1) {
      user.permissions.push(ownership);
      messages.push('Admin ownership added');
      shouldSave = true;
    } else {
      messages.push('Admin already has ownership');
    }
    if(shouldSave)
      await user.save();
  }
  return user;
};

Aucun commentaire:

Enregistrer un commentaire