github.com/oinume/lekcije@v0.0.0-20231017100347-5b4c5eb6ab24/frontend/src/http/graphql.ts (about)

     1  import cookie from 'cookie';
     2  import {GraphQLClient} from 'graphql-request';
     3  
     4  export const createGraphQLClient = (path?: string, token?: string) => {
     5    const headers: Record<string, string> = {
     6      'Content-Type': 'application/json',
     7    };
     8  
     9    if (path === undefined) {
    10      path = '/graphql';
    11    }
    12  
    13    if (token === undefined) {
    14      const cookies = cookie.parse(document.cookie);
    15      if (cookies.apiToken) {
    16        headers.Authorization = `Bearer ${cookies.apiToken}`;
    17      }
    18    } else {
    19      headers.Authorization = `Bearer ${token}`;
    20    }
    21  
    22    return new GraphQLClient(path, {
    23      headers,
    24    });
    25  };
    26  
    27  type ErrorExtensions = {
    28    code?: string;
    29    localizedMessage?: string;
    30  };
    31  
    32  type ErrorInfo = {
    33    path: string;
    34    message: string;
    35    extensions: ErrorExtensions;
    36  };
    37  
    38  export type GraphQLError = {
    39    response: {errors: ErrorInfo[]};
    40  };
    41  
    42  export const toMessage = (error: GraphQLError, defaultMessage?: string): string => {
    43    const errs = error.response.errors;
    44    if (errs.length === 0) {
    45      return '';
    46    }
    47  
    48    return `${errs[0].extensions.localizedMessage ?? defaultMessage ?? ''} (${errs[0].extensions.code ?? ''})`;
    49  };