http put() to update a field

Hi,
Thanks in advance for checking this.
I am trying to update the proxy field of the YouTube collection through the api call and I have wrote below backend call.
The code response with status code 200 but the field in the collection is not getting updated.

export function put_youtube(request) {
  let options = {
    "headers": {
      "Content-Type": "application/json"
    }
  };

  return request.body.json()
    .then((item) => {
      return wixData.query("youtube_lic")
        .eq("_id", item._id)
        .find()
        .then((results) => {
          if (results.items.length > 0) {
            return results.items[0];
          } else {
            return Promise.reject(new Error("Item not found"));
          }
        });
    })
    .then((item) => {
      if (item && item._id ) {
        const itemId = item._id;
        const proxy = item.proxy;
        return wixData.update("youtube_lic", {_id: itemId, proxy: proxy});
      } else {
        return Promise.reject(new Error("Item not found or proxy field already exists"));
      }
    })
    .then((results) => {
      options.body = {
        "inserted": results
      };
      return ok(options);
    })
    .catch((error) => {
      options.body = {
        "error": error.message
      };
      return serverError(options);
    });
}

You’re using the variable item in several places but in each place it refers to a different object. If you read your code carefully you’ll see that you get an item from the database and then assign it it own values (the values it already has) instead of using the item you got with the response. Here is a suggestion:

import {ok, notFound, serverError} from 'wix-http-functions';
export function put_youtube(request) {
let requestBody = {};
  let options = {
    "headers": {
      "Content-Type": "application/json"
    }
  };

  return request.body.json()
    .then(res => {
requestBody = res;
     return wixData.get("youtube_lic", requestBody._id)
})
  .then(dataObject => {
if(!dataObject){return Promise.reject('notFound');}
dataObject.proxy = requestBody.proxy;
return wixData.update("youtube_lic", dataObject);
    })
    .then((results) => {
      options.body = {
        "inserted": results
      };
      return ok(options);
    })
    .catch((error) => {
      options.body = {
        "error": error.message
      };
      return error === 'notFound' ? notFound(options) : serverError(options);
    });
}

Thank you so much for your kind help, I changed the code according to your suggestion and it worked great.

1 Like