mardi 13 mars 2018

How to elegantly query for a record and create it if it does not exist yet?

The Goal

The goal of startChat(partner_profile) is to get the id of a chat between two users to then be able to redirect to this chat. There are two different cases:

  1. a chat between them already exists

    a) partner_profile is first participant

    b) partner_profile is second participant

  2. the chat between them needs to be created first

What I got so far

I know how to get an ID for each of the above listed cases, but I do not know how to combine them all. Here is my code so far:

 startChat(partner_profile) {
      // case 1a
      this.get('store').queryRecord('chat', {
              first_participant: partner_profile.id
       }).then(function(chat) {
              let id = chat.get('id');
              onSaveSuccess(id);
       }).catch(function(){
      });

      // case 1b
     this.get('store').queryRecord('chat', {
             second_participant: partner_profile.id
     }).then(function(chat) {
            let id = chat.get('id');
            onSaveSuccess(id);
            return;
     }).catch(function(){
         // **error handling* 
    });

    // case 2
    let chat = this.get('store').createRecord('chat', {
        second_participant: partner_profile
    });

    let onSaveSuccess = (id) => this.transitionToRoute('chats.chat',id);

    chat.save()
        .then(function(success) {
            let id = success.get('id');
            onSaveSuccess(id);
         })
        .catch((error) => {
           // **error handling*
      }
    });

How can I combine those cases?

Right now it's really ugly, because every case is executed and of course two of them fail. How could I do this in a nicer way? Is there a way to get_or_create a record at once (like there is in Django)? Thank you for your help :-)




Aucun commentaire:

Enregistrer un commentaire