simple-graphql-client.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { DocumentNode } from 'graphql';
  2. import { GraphQLClient } from 'graphql-request';
  3. import { GraphQLError } from 'graphql-request/dist/src/types';
  4. import { print } from 'graphql/language/printer';
  5. import { AttemptLogin, AttemptLoginVariables } from 'shared/generated-types';
  6. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from 'shared/shared-constants';
  7. import { ATTEMPT_LOGIN } from '../../admin-ui/src/app/data/definitions/auth-definitions';
  8. import { getConfig } from '../src/config/vendure-config';
  9. // tslint:disable:no-console
  10. /**
  11. * A minimalistic GraphQL client for populating and querying test data.
  12. */
  13. export class SimpleGraphQLClient {
  14. private client: GraphQLClient;
  15. private authToken: string;
  16. private channelToken: string;
  17. constructor(apiUrl: string = '') {
  18. this.client = new GraphQLClient(apiUrl);
  19. }
  20. setAuthToken(token: string) {
  21. this.authToken = token;
  22. this.setHeaders();
  23. }
  24. setChannelToken(token: string) {
  25. this.channelToken = token;
  26. this.setHeaders();
  27. }
  28. query<T = any, V = Record<string, any>>(query: DocumentNode, variables?: V): Promise<T> {
  29. const queryString = print(query);
  30. return this.client.request(queryString, variables);
  31. }
  32. queryRaw<T = any, V = Record<string, any>>(
  33. query: DocumentNode,
  34. variables?: V,
  35. ): Promise<{
  36. data?: T;
  37. extensions?: any;
  38. headers: Record<string, string>;
  39. status: number;
  40. errors?: GraphQLError[];
  41. }> {
  42. const queryString = print(query);
  43. return this.client.rawRequest<T>(queryString, variables);
  44. }
  45. async queryStatus<T = any, V = Record<string, any>>(query: DocumentNode, variables?: V): Promise<number> {
  46. const queryString = print(query);
  47. const result = await this.client.rawRequest<T>(queryString, variables);
  48. return result.status;
  49. }
  50. async asUserWithCredentials(username: string, password: string) {
  51. const result = await this.query<AttemptLogin, AttemptLoginVariables>(ATTEMPT_LOGIN, {
  52. username,
  53. password,
  54. });
  55. if (result.login) {
  56. this.setAuthToken(result.login.authToken);
  57. } else {
  58. console.error(result);
  59. }
  60. }
  61. async asSuperAdmin() {
  62. await this.asUserWithCredentials(SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD);
  63. }
  64. asAnonymousUser() {
  65. this.setAuthToken('');
  66. }
  67. private setHeaders() {
  68. this.client.setHeaders({
  69. Authorization: `Bearer ${this.authToken}`,
  70. [getConfig().channelTokenKey]: this.channelToken,
  71. });
  72. }
  73. }