woocommerce / woocommerce-rest-api-js-lib

New JavaScript library for WooCommerce REST API
https://www.npmjs.com/package/@woocommerce/woocommerce-rest-api
MIT License
286 stars 75 forks source link

Remove Unnecessary JSON.stringify #111

Open notmike101 opened 2 years ago

notmike101 commented 2 years ago

Axios "automagically" stringfies the post body, there's no need to pre-stringify.

Pre-stringifying can result in unexpected behavior when you're passing in JSON content that includes quotes, such as { name: "My name is \"Mike\"" }

notmike101 commented 2 years ago

For anyone who lands here from a search engine looking for a fix and doesn't want to install my fork, you can patch this yourself in your own code by doing the following:

(This assumes you're initializing WooCommerceRestAPI and storing it in a variable named api, just like the README example)

api._request = function(method, endpoint, data, params = {}) {
  const url = this._getUrl(endpoint, params);

  const headers = {
    Accept: "application/json"
  };
  // only set "User-Agent" in node environment
  // the checking method is identical to upstream axios
  if (
    typeof process !== "undefined" &&
    Object.prototype.toString.call(process) === "[object process]"
  ) {
    headers["User-Agent"] =
      "WooCommerce REST API - JS Client/" + this.classVersion;
  }

  let options = {
    url: url,
    method: method,
    responseEncoding: this.encoding,
    timeout: this.timeout,
    responseType: "json",
    headers
  };

  if (this.isHttps) {
    if (this.queryStringAuth) {
      options.params = {
        consumer_key: this.consumerKey,
        consumer_secret: this.consumerSecret
      };
    } else {
      options.auth = {
        username: this.consumerKey,
        password: this.consumerSecret
      };
    }

    options.params = { ...options.params, ...params };
  } else {
    options.params = this._getOAuth().authorize({
      url: url,
      method: method
    });
  }

  if (data) {
    options.headers["Content-Type"] = "application/json;charset=utf-8";
    // WHY THE FUCK DID THEY DO THIS?
    // options.data = JSON.stringify(data);
  }

  // Allow set and override Axios options.
  options = { ...options, ...this.axiosConfig };

  return axios(options);
}

After you implement this patch, you use this library as normal but will no longer run into errors because of this.