apivue.jsvue-resource

Vue resource, using the same form for inserts and updates


I'm using Vue resource to connect to my backend api. I have a form component which I use for both creating a new resource item and modifying existing resource items. The form works fine, but when I want to save the form, it needs to use the proper http method for the api call. If I am creating a new item, it should use the POST method, and if I'm updating an existing item it should use the PUT method. Right now, my form save method looks something like this:

    if (this.itemId > 0) {   // Update existing item
        myresource.update({id: this.itemId}, this.item).then(response => {
            //...
        }, response => {
            //...
        });
    }
    else {      // Post new item
        myresource.save({}, this.item).then(response => {
            //...
        }, response => {
            //...
        });
    }

Basically, I have to use an if statement to check whether to use the update or save resource functions, then the success/fail promises both use the same code. Is there some way to combine the two methods above with something like this:

    var method = this.itemId ? 'PUT' : 'POST';
    myresource.request(method, {id: this.itemId}, this.item).then(response => {
            //...
        }, response => {
            //...
        });

The above code obviously doesn't work, but is there a similar way to accomplish this without using an if statement and repeating my success/fail promises for each request type?


Solution

  • One simple option would be to create the request based on the conditions and then connect the remaining promises in a single chain:

        const request = (this.itemId > 0) ? myresource.update ? myresource.save;
        request({
          id: this.itemId // Make the save call ignore the id
        }, this.item).then(response => {
          // Shared code
        });