Configure the client

The getSDK gives you an SDK client for your GraphQL API

import { GraphQLClient } from "graphql-request";
import { getSdk } from "../graphqlSDKGenerator/graphqlSDKGenerator";

const initializeSDK = () => {
  const client = new GraphQLClient(
    "https://your-end-point/",
    {
      headers: {
        Authorization: 'Bearer xxx',
      },
    }
  );

  return getSdk(client);
};

const main = async () => {
  const sdkInstance = initializeSDK();
};

main();

Custom logger

We can pass a custom function which can be used to log the output and help in debugging. You can check live example here.

import { GraphQLClient } from "graphql-request";
import { getSdk, SdkFunctionWrapper } from "../graphqlSDKGenerator/graphqlSDKGenerator";

const clientTimingWrapper: SdkFunctionWrapper = async <T>(
  action: () => Promise<T>,
  operationName: string,
  operationType?: string
): Promise<T> => {
  const startTime = new Date();
  const result: Awaited<T> = await action();
  console.log(
    `YOUR_SDK ${Object.keys(result as any)[0]} ${operationType} took ${
      (new Date() as any) - (startTime as any)
    } (ms)`
  );
  return result;
};

const initializeSDK = () => {
  const client = new GraphQLClient(
    "https://your-end-point/",
    {
      headers: {
        Authorization: 'Bearer xxx',
      },
    }
  );

  return getSdk(client,clientTimingWrapper);
};

const main = async () => {
  const sdkInstance = initializeSDK();
};

main();

Pass dynamic headers at runtime

You can pass a function to the headers field to pull the headers at query time, this way you can make requests if user changes during the session.

import { GraphQLClient } from "graphql-request";
import { getSdk } from "../graphqlSDKGenerator/graphqlSDKGenerator";

const initializeSDK = (authToken:string) => {
  const client = new GraphQLClient(
    "https://your-end-point/",
    {
      headers: {
        Authorization: `Bearer ${authToken}`,
      },
    }
  );

  return getSdk(client);
};

const main = async () => {
  let sdkInstance = initializeSDK(authToken);
  
  // after some operations 
  user.logout()
  // again user logs in
  sdkInstance = initializeSDK(authToken)
};

main();

Last updated