All files / src/clients/graphql graphql_client.ts

100% Statements 23/23
100% Branches 10/10
100% Functions 3/3
100% Lines 21/21

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 434x 4x 4x 4x 4x 4x       4x     21x 21x 1x     20x     4x 26x 1x     25x       25x       25x 2x   23x     25x   4x  
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 class GraphqlClient {
  private readonly client: HttpClient;
 
  constructor(readonly domain: string, readonly token?: string) {
    if (!Context.IS_PRIVATE_APP && !token) {
      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.');
    }
 
    params.extraHeaders = {
      [ShopifyHeader.AccessToken]: Context.IS_PRIVATE_APP ? Context.API_SECRET_KEY : this.token as string,
      ...params.extraHeaders,
    };
    const path = `/admin/api/${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});
  }
}