All files EtsyClientV2.js

93.33% Statements 210/225
87.67% Branches 64/73
100% Functions 29/29
93.33% Lines 210/225

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 2251x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 1x 1x 1x 1x 4x 4x 4x 1x 1x 31x 31x 1x 1x 1x 3x 3x 1x 1x 1x 2x 2x 2x 1x 1x 1x 2x 2x 2x 1x 1x 1x 2x 2x 2x 1x 1x 1x 4x 4x 4x 1x 1x 1x 2x 2x 2x 1x 1x 1x 4x 4x 4x 1x 1x 1x 2x 2x 2x 1x 1x 1x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 1x 1x 27x 27x 16x 27x 11x 11x 11x 11x 11x 27x 1x 1x 27x 27x 27x 27x 27x 27x 27x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 1x 1x 5x 2x 2x 5x 5x 1x 1x 3x 3x 1x 1x 27x 27x 27x 24x 24x 27x 27x 1x 1x 26x 26x 26x 26x 26x 26x 1x 1x 27x 26x 26x 27x 27x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x   26x 26x 26x 26x 26x             26x 26x 1x 1x 26x 26x 26x 26x 26x 26x     26x 26x 26x             26x 26x 1x 1x
import queryString from 'query-string';
import fetch from 'node-fetch';
import SusiRali from 'susi-rali';
 
const DEFAULT_DRY_MODE = false;// DEBUG // if true, then print fetch onto console instead of calling etsy
 
/**
 * this utility class implement ETSY (some) methods documented here:
 * https://www.etsy.com/developers/documentation/getting_started/api_basics#reference > API V2 Reference
 **/
class EtsyClientV2 {
 
  static debug = process.env.ETSY_DEBUG && process.env.ETSY_DEBUG === true;
 
  constructor(options) {
    if (!options) {
      options = {};
    }
    this.apiUrl = "apiUrl" in options ? options.apiUrl : (process.env.ETSY_API_ENDPOINT || 'https://openapi.etsy.com/v2');
    this._assumeApiUrl();
    this.apiKey = "apiKey" in options ? options.apiKey : process.env.ETSY_API_KEY;
    this._assumeApiKey();
    this.shop   = "shop" in options ? options.shop : process.env.ETSY_SHOP;
    this.lang   = "lang" in options ? options.lang : process.env.ETSY_LANG;
    // configure rate limit on etsy call : max <etsyRateMaxQueries> per <etsyRateWindowSizeMs> ms
    // Etsy rate limit doc (10/sec) : https://www.etsy.com/developers/documentation/getting_started/api_basics#section_rate_limiting
    this.etsyRateWindowSizeMs = "etsyRateWindowSizeMs" in options ? options.etsyRateWindowSizeMs : (process.env.ETSY_RATE_WINDOWS_SIZE_MS  || 1000);
    this.etsyRateMaxQueries   = "etsyRateMaxQueries" in options ? options.etsyRateMaxQueries : (process.env.ETSY_RATE_MAX_QUERIES || null);
    this.dryMode              = "dryMode" in options ? options.dryMode : ("true" === process.env.ETSY_DRY_MODE || DEFAULT_DRY_MODE);
    this.initRateLimiter();
    // DEBUG // console.debug(`EtsyClientV2 - apiUrl:${this.apiUrl} - dryMode:${this.dryMode} - ${this.limiterDesc}`);
  }
 
  initRateLimiter() {
    this.limiter = (this.etsyRateWindowSizeMs === null || this.etsyRateMaxQueries === null) ? null :
      new SusiRali({
          windowsMs:this.etsyRateWindowSizeMs,
          maxQueryPerWindow:this.etsyRateMaxQueries,
          debugEnabled: false
      });
    this.limiterDesc = (!this.isRateLimitEnabled()) ? "" : `Rate limit of ${this.etsyRateMaxQueries} queries per ${this.etsyRateWindowSizeMs}ms`;
  }
 
  isRateLimitEnabled() {
    return this.limiter !== null;
  }
 
  // https://www.etsy.com/developers/documentation/reference/shop#method_findallshops
  findAllShops(options) {
    return this.limitedEtsyApiFetch(`/shops`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/shop#method_getshop
  getShop(options) {
     this._assumeShop();
     return this.limitedEtsyApiFetch(`/shops/${this.shop}`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/shopsection#method_findallshopsections
  findAllShopSections(options) {
     this._assumeShop();
     return this.limitedEtsyApiFetch(`/shops/${this.shop}/sections`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/listing#method_findallshoplistingsactive
  findAllShopListingsActive(options) {
     this._assumeShop();
     return this.limitedEtsyApiFetch(`/shops/${this.shop}/listings/active`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/listing#method_getlisting
  getListing(listingId, options) {
     this._assumeField('listingId', listingId);
     return this.limitedEtsyApiFetch(`/listings/${listingId}`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/listingvariationimage#method_getvariationimages
  getVariationImages(listingId, options) {
     this._assumeField('listingId', listingId);
     return this.limitedEtsyApiFetch(`/listings/${listingId}/variation-images`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/listingimage#method_findalllistingimages
  findAllListingImages(listingId, options) {
     this._assumeField('listingId', listingId);
     return this.limitedEtsyApiFetch(`/listings/${listingId}/images`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/listinginventory
  getInventory(listingId, options) {
     this._assumeField('listingId', listingId);
     return this.limitedEtsyApiFetch(`/listings/${listingId}/inventory`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/propertyvalue#method_getattribute
  getAttributes(listingId, options) {
     this._assumeField('listingId', listingId);
     return this.limitedEtsyApiFetch(`/listings/${listingId}/attributes`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/listingproduct#method_getproduct
  getProduct(listingId, productId, options) {
     this._assumeField('listingId', listingId);
     this._assumeField('productId', productId);
     return this.limitedEtsyApiFetch(`/listings/${listingId}/products/${productId}`, options);
  }
 
  // https://www.etsy.com/developers/documentation/reference/shippinginfo#method_findalllistingshippingprofileentries
  findAllListingShippingProfileEntries(listingId, options) {
     this._assumeField('listingId', listingId);
     return this.limitedEtsyApiFetch(`/listings/${listingId}/shipping/info`, options);
  }
 
  limitedEtsyApiFetch(endpoint, options) {
    var client = this;
    if (!client.isRateLimitEnabled()) {
      return client.safeEtsyApiFetch(endpoint, options);
    } else {
      return new Promise(async function(resolve, reject) {
        await client.limiter.limitedCall(() => client.safeEtsyApiFetch(endpoint, options))
                  .then(resolve).catch(reject);
      });
    }
  }
 
  safeEtsyApiFetch(endpoint, options) {
     this._assumeField('endpoint', endpoint);
     var client = this;
     return new Promise((resolve, reject) => {
         const getQueryString = queryString.stringify(client.getOptions(options));
         client.nodeFetch(`${client.apiUrl}${endpoint}?${getQueryString}`)
           .then(response => EtsyClientV2._response(response, resolve, reject))
           .catch((fetchError) => {
             var secureError = {};
             client.secureErrorAttribute(secureError, fetchError, "message");
             client.secureErrorAttribute(secureError, fetchError, "reason");
             client.secureErrorAttribute(secureError, fetchError, "type");
             client.secureErrorAttribute(secureError, fetchError, "errno");
             client.secureErrorAttribute(secureError, fetchError, "code");
             reject(secureError);
           });
     });
  }
 
  secureErrorAttribute(secureError, sourceError, attribute) {
    if (!Object.keys(sourceError).includes(attribute)) {
      return;
    }
    secureError[attribute] = this.secureAttributeValue(sourceError[attribute]);
  }
 
  secureAttributeValue(value) {
    return (value === null || value === undefined) ? null : value.replace(new RegExp(this.apiKey,'g'), "**hidden**");
  }
 
  getOptions(options) {
    var merged = options ? options : {};
    merged['api_key'] = this.apiKey;
    if (this.lang != null && !("language" in merged)) {
      merged['language'] = this.lang;
    }
    return merged;
  }
 
  dryFetch(endpoint) {
    const response = {};
    response.ok = true;
    response.text = function(){ return JSON.stringify({endpoint});};
    console.log(`[dry_fetch] ${endpoint}`);
    return Promise.resolve(response);
  }
 
  nodeFetch(endpoint) {
    if (this.dryMode) {
      return this.dryFetch(endpoint);
    }
    return fetch(endpoint);
  }
 
  _assumeShop() { if (!this.shop) { throw "shop is not defined";  } }
  _assumeApiUrl() { if (!this.apiUrl) { throw "apiUrl is required. ie. set ETSY_API_ENDPOINT environment variable.";  } }
  _assumeApiKey() { if (!this.apiKey) { throw "apiKey is required. ie. set ETSY_API_KEY environment variable.";  } }
  _assumeField(fieldName, fieldValue) { if (!fieldValue) { throw fieldName + " is required";  } }
 
  static _response(response, resolve, reject) {
    EtsyClientV2._consumeResponseBodyAs(response,
      (json) => {
        if (!response.ok) {
          reject((json && json.details) || (json && json.message) || response.status);
        } else {
          resolve(json);
        }
      },
      (txt) => {
        if (!response.ok) {
          reject(txt);
        } else {
          resolve(txt);// some strange case
        }
      }
    );
  }
 
  static _consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
    (async () => {
      var responseString = await response.text();
      try{
        if (responseString && typeof responseString === "string"){
         var responseParsed = JSON.parse(responseString);
         if (EtsyClientV2.debug) {
            console.log("RESPONSE(Json)", responseParsed);
         }
         return jsonConsumer(responseParsed);
        }
      } catch(error) {
        // text is not a valid json so we will consume as text
      }
      if (EtsyClientV2.debug) {
        console.log("RESPONSE(Txt)", responseString);
      }
      return txtConsumer(responseString);
    })();
  }
}
export default EtsyClientV2;