All files / src/clients/http_client http_client.ts

96.53% Statements 139/144
95.06% Branches 77/81
100% Functions 26/26
97.12% Lines 135/139

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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298  15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   126x 126x 126x         15x 57x 57x 57x             15x 81x 81x 81x             15x 5x 5x 5x             15x 5x 5x 5x       15x 148x   6x 6x 6x         148x 349x   148x 148x 1x   147x 147x 19x   147x 106x 1x 1x   105x 2x     147x 147x 147x 86x 86x 85x   40x 40x   3x       3x   42x 42x   85x     147x 147x         147x 147x   153x 153x   153x 153x 153x   21x 21x 21x 13x 6x 6x   1x   6x   6x 6x     7x 1x   6x     14x                   15x 147x   15x 153x   153x 479x   153x 153x   153x 152x   152x 152x 132x   6x       6x   1x   6x       6x     5x 5x 1x 1x 1x           4x       132x           20x 20x 17x   20x 3x   20x     20x 20x 20x 20x   5x 5x                   8x               7x                     21x 21x 20x     1x                 15x   15x 15x   15x                                        
import querystring, {ParsedUrlQueryInput} from 'querystring';
import crypto from 'crypto';
import fs from 'fs';
 
import fetch, {RequestInit, Response} from 'node-fetch';
import {Method, StatusCode} from '@shopify/network';
 
import * as ShopifyErrors from '../../error';
import {SHOPIFY_API_LIBRARY_VERSION} from '../../version';
import {Context} from '../../context';
import ProcessedQuery from '../../utils/processed-query';
 
import {
  DataType,
  DeleteRequestParams,
  GetRequestParams,
  PostRequestParams,
  PutRequestParams,
  RequestParams,
  RequestReturn,
} from './types';
 
interface DeprecationInterface {
  message: string | null;
  path: string;
  body?: string;
}
 
export class HttpClient {
  // 1 second
  static readonly RETRY_WAIT_TIME = 1000;
  // 5 minutes
  static readonly DEPRECATION_ALERT_DELAY = 300000;
  private LOGGED_DEPRECATIONS: {[key: string]: number} = {};
 
  public constructor(private domain: string) {
    this.domain = domain;
  }
 
  /**
   * Performs a GET request on the given path.
   */
  public async get<T = unknown>(params: GetRequestParams) {
    return this.request<T>({method: Method.Get, ...params});
  }
 
  /**
   * Performs a POST request on the given path.
   */
  public async post<T = unknown>(params: PostRequestParams) {
    return this.request<T>({method: Method.Post, ...params});
  }
 
  /**
   * Performs a PUT request on the given path.
   */
  public async put<T = unknown>(params: PutRequestParams) {
    return this.request<T>({method: Method.Put, ...params});
  }
 
  /**
   * Performs a DELETE request on the given path.
   */
  public async delete<T = unknown>(params: DeleteRequestParams) {
    return this.request<T>({method: Method.Delete, ...params});
  }
 
  protected async request<T = unknown>(
    params: RequestParams,
  ): Promise<RequestReturn<T>> {
    const maxTries = params.tries ? params.tries : 1;
    if (maxTries <= 0) {
      throw new ShopifyErrors.HttpRequestError(
        `Number of tries must be >= 0, got ${maxTries}`,
      );
    }
 
    let userAgent = `Shopify API Library v${SHOPIFY_API_LIBRARY_VERSION} | Node ${process.version}`;
 
    if (Context.USER_AGENT_PREFIX) {
      userAgent = `${Context.USER_AGENT_PREFIX} | ${userAgent}`;
    }
 
    if (params.extraHeaders) {
      if (params.extraHeaders['user-agent']) {
        userAgent = `${params.extraHeaders['user-agent']} | ${userAgent}`;
        delete params.extraHeaders['user-agent'];
      } else if (params.extraHeaders['User-Agent']) {
        userAgent = `${params.extraHeaders['User-Agent']} | ${userAgent}`;
      }
    }
 
    let headers: typeof params.extraHeaders = {
      ...params.extraHeaders,
      'User-Agent': userAgent,
    };
    let body = null;
    if (params.method === Method.Post || params.method === Method.Put) {
      const {type, data} = params as PostRequestParams;
      if (data) {
        switch (type) {
          case DataType.JSON:
            body = typeof data === 'string' ? data : JSON.stringify(data);
            break;
          case DataType.URLEncoded:
            body =
              typeof data === 'string'
                ? data
                : querystring.stringify(data as ParsedUrlQueryInput);
            break;
          case DataType.GraphQL:
            body = data as string;
            break;
        }
        headers = {
          ...headers,
          'Content-Type': type,
          'Content-Length': Buffer.byteLength(body as string),
        };
      }
    }
I
    const url = `https://${this.domain}${this.getRequestPath(
      params.path,
    )}${ProcessedQuery.stringify(params.query)}`;
    const options: RequestInit = {
      method: params.method.toString(),
      headers,
      body,
    } as RequestInit;
 
    async function sleep(waitTime: number): Promise<void> {
      return new Promise((resolve) => setTimeout(resolve, waitTime));
    }
 
    let tries = 0;
    while (tries < maxTries) {
      try {
        return await this.doRequest<T>(url, options);
      } catch (error) {
        tries++;
        if (error instanceof ShopifyErrors.HttpRetriableError) {
          // We're not out of tries yet, use them
          if (tries < maxTries) {
            let waitTime = HttpClient.RETRY_WAIT_TIME;
            if (
              error instanceof ShopifyErrors.HttpThrottlingError &&
              error.response.retryAfter
            ) {
              waitTime = error.response.retryAfter * 1000;
            }
            await sleep(waitTime);
            continue;
          }
 
          // We're set to multiple tries but ran out
          if (maxTries > 1) {
            throw new ShopifyErrors.HttpMaxRetriesError(
              `Exceeded maximum retry count of ${maxTries}. Last message: ${error.message}`,
            );
          }
        }
 
        // We're not retrying or the error is not retriable, rethrow
        throw error;
      }
    }
 
    // We're never supposed to come this far, this is here only for the benefit of Typescript
    /* istanbul ignore next */
    throw new ShopifyErrors.ShopifyError(
      `Unexpected flow, reached maximum HTTP tries but did not throw an error`,
    );
  }
 
  protected getRequestPath(path: string): string {
    return `/${path.replace(/^\//, '')}`;
  }
 
  private async doRequest<T = unknown>(
    url: string,
    options: RequestInit,
  ): Promise<RequestReturn<T>> {
    try {
      const response: Response = await fetch(url, options);
      const body = await response.json().catch(() => ({}));
 
      if (response.ok) {
        if (
          response.headers &&
          response.headers.has('X-Shopify-API-Deprecated-Reason')
        ) {
          const deprecation: DeprecationInterface = {
            message: response.headers.get('X-Shopify-API-Deprecated-Reason'),
            path: url,
          };
 
          if (options.body) {
            // This can only be a string, since we're always converting the body before calling this method
            deprecation.body = `${(options.body as string).substring(
              0,
              100,
            )}...`;
          }
 
          const depHash = crypto
            .createHash('md5')
            .update(JSON.stringify(deprecation))
            .digest('hex');
 
          if (
            !Object.keys(this.LOGGED_DEPRECATIONS).includes(depHash) ||
            Date.now() - this.LOGGED_DEPRECATIONS[depHash] >=
              HttpClient.DEPRECATION_ALERT_DELAY
          ) {
            this.LOGGED_DEPRECATIONS[depHash] = Date.now();
 
            if (Context.LOG_FILE) {
              const stack = new Error().stack;
              const log = `API Deprecation Notice ${new Date().toLocaleString()} : ${JSON.stringify(
                deprecation,
              )}\n    Stack Trace: ${stack}\n`;
              fs.writeFileSync(Context.LOG_FILE, log, {
                flag: 'a',
                encoding: 'utf-8',
              });
            } else {
              console.warn('API Deprecation Notice:', deprecation);
            }
          }
        }
 
        return {
          body,
          headers: response.headers,
        };
      } else {
        const errorMessages: string[] = [];
        if (body.errors) {
          errorMessages.push(JSON.stringify(body.errors, null, 2));
        }
        if (response.headers && response.headers.get('x-request-id')) {
          errorMessages.push(
            `If you report this error, please include this id: ${response.headers.get(
              'x-request-id',
            )}`,
          );
        }
 
        const errorMessage = errorMessages.length
          ? `:\n${errorMessages.join('\n')}`
          : '';
        const headers = response.headers.raw();
        const code = response.status;
        const statusText = response.statusText;
 
        switch (true) {
          case response.status === StatusCode.TooManyRequests: {
            const retryAfter = response.headers.get('Retry-After');
            throw new ShopifyErrors.HttpThrottlingError({
              message: `Shopify is throttling requests${errorMessage}`,
              code,
              statusText,
              body,
              headers,
              retryAfter: retryAfter ? parseFloat(retryAfter) : undefined,
            });
          }
          case response.status >= StatusCode.InternalServerError:
            throw new ShopifyErrors.HttpInternalError({
              message: `Shopify internal error${errorMessage}`,
              code,
              statusText,
              body,
              headers,
            });
          default:
            throw new ShopifyErrors.HttpResponseError({
              message: `Received an error response (${response.status} ${response.statusText}) from Shopify${errorMessage}`,
              code,
              statusText,
              body,
              headers,
            });
        }
      }
    } catch (error) {
      if (error instanceof ShopifyErrors.ShopifyError) {
        throw error;
      } else {
        throw new ShopifyErrors.HttpRequestError(
          `Failed to make Shopify HTTP request: ${error}`,
        );
      }
    }
  }
}