0

I have a user model where only user_email(primary key/ID) is mandatory, all other properties are nullables. I have a user service which uses a UserRepository for CRUD operations. I'm trying to create an UPSERT functionality that to handle Users in my PostreSQL DB.

The code on the service is the following:

async upsertUser(user: User): Promise<User> {  
    try {
      await this.userRepository.replaceById(user.user_email, user);
    } catch {
      return this.userRepository.create(user);
    }
    return user;
  }

Note: I also tried to use the save method.

The problem is I don't know how can I ignore NULL properties. I don't want to update all columns at once. Let's say I just want to update session info on my database. I'm trying the following code:

const user: User = new User({
    user_email: this.currentUser.email,
    last_login_at: userSession.authTime,
    session_id: userSession.cookieSession,
    sys_modify_date: (new Date).toISOString()
});
await this.userService.upsertUser(user);

The problem of this, is that it will replace everything. If I have my user_fullname property set from a previous creation, it will be updated as NULL because the User class object has not this property filled.

How I can I ignore and not update NULL properties?

1 Answer 1

0

You can use updateById instead of replaceById with lodash pickBy function.

firstly, remove nullish properties:

How to remove undefined and null values from an object using lodash?

then:

this.userRepository.updateById(user.user_email, user);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.