All files / src/clients/graphql graphql_client.ts

100% Statements 36/36
100% Branches 14/14
100% Functions 6/6
100% Lines 36/36

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  6x 6x 6x 6x 6x 6x 6x 6x 6x   51x 51x 51x 51x 1x   50x   6x 62x     62x 123x   62x 1x   61x 61x 61x 61x 20x     41x   61x   61x 61x 2x         59x         6x 59x             6x   6x              
import {Context} from '../../context';
import {ShopifyHeader} from '../../base-types';
import {HttpClient} from '../http_client/http_client';
import {DataType, RequestReturn} from '../http_client/types';
import * as ShopifyErrors from '../../error';
 
import {GraphqlParams} from './types';
 
export interface AccessTokenHeader {
  header: string;
  value: string;
}
 
export class GraphqlClient {
  protected baseApiPath = '/admin/api';
 
  private readonly client: HttpClient;
 
  constructor(readonly domain: string, readonly accessToken?: string) {
    if (!Context.IS_PRIVATE_APP && !accessToken) {
      throw new ShopifyErrors.MissingRequiredArgument(
        'Missing access token when creating GraphQL client',
      );
    }
 
    this.client = new HttpClient(this.domain);
  }
 
  async query<T = unknown>(params: GraphqlParams): Promise<RequestReturn<T>> {
    if (params.data.length === 0) {
      throw new ShopifyErrors.MissingRequiredArgument('Query missing.');
    }
 
    const accessTokenHeader = this.getAccessTokenHeader();
    params.extraHeaders = {
      [accessTokenHeader.header]: accessTokenHeader.value,
      ...params.extraHeaders,
    };
 
    const path = `${this.baseApiPath}/${Context.API_VERSION}/graphql.json`;
 
    let dataType: DataType.GraphQL | DataType.JSON;
 
    if (typeof params.data === 'object') {
      dataType = DataType.JSON;
    } else {
      dataType = DataType.GraphQL;
    }
 
    const result = await this.client.post<T>({path, type: dataType, ...params});
 
    if ((result.body as unknown as {[key: string]: unknown}).errors) {
      throw new ShopifyErrors.GraphqlQueryError({
        message: 'GraphQL query returned errors',
        response: result.body as unknown as {[key: string]: unknown},
      });
    }
    return result;
  }
 
  protected getAccessTokenHeader(): AccessTokenHeader {
    return {
      header: ShopifyHeader.AccessToken,
      value: Context.IS_PRIVATE_APP
        ? Context.API_SECRET_KEY
        : (this.accessToken as string),
    };
  }
}