All files / src/clients/graphql graphql_client.ts

100% Statements 32/32
100% Branches 10/10
100% Functions 6/6
100% Lines 32/32

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  5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   29x 29x 29x 29x 1x   28x   5x 39x     39x 39x 1x   38x 38x 38x 38x 2x     36x   38x       5x 36x             5x   5x                      
import {MissingRequiredArgument} from '../../error';
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(params: GraphqlParams): Promise<RequestReturn> {
    if (params.data.length === 0) {
      throw new 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;
    }
 
    return this.client.post({path, type: dataType, ...params});
  }
 
  protected getAccessTokenHeader(): AccessTokenHeader {
    return {
      header: ShopifyHeader.AccessToken,
      value: Context.IS_PRIVATE_APP
        ? Context.API_SECRET_KEY
        : (this.accessToken as string),
    };
  }
}