simple-graphql-client.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /// <reference types="../typings" />
  2. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '@vendure/common/lib/shared-constants';
  3. import { DocumentNode } from 'graphql';
  4. import { GraphQLClient } from 'graphql-request';
  5. import gql from 'graphql-tag';
  6. import { print } from 'graphql/language/printer';
  7. import { Curl } from 'node-libcurl';
  8. import { CREATE_ASSETS } from '../../../admin-ui/src/app/data/definitions/product-definitions';
  9. import { ImportInfo } from '../e2e/graphql/generated-e2e-admin-types';
  10. import { getConfig } from '../src/config/config-helpers';
  11. import { createUploadPostData } from './create-upload-post-data';
  12. // tslint:disable:no-console
  13. /**
  14. * A minimalistic GraphQL client for populating and querying test data.
  15. */
  16. export class SimpleGraphQLClient {
  17. private client: GraphQLClient;
  18. private authToken: string;
  19. private channelToken: string;
  20. constructor(private apiUrl: string = '') {
  21. this.client = new GraphQLClient(apiUrl);
  22. }
  23. setAuthToken(token: string) {
  24. this.authToken = token;
  25. this.setHeaders();
  26. }
  27. getAuthToken(): string {
  28. return this.authToken;
  29. }
  30. setChannelToken(token: string) {
  31. this.channelToken = token;
  32. this.setHeaders();
  33. }
  34. /**
  35. * Performs both query and mutation operations.
  36. */
  37. async query<T = any, V = Record<string, any>>(query: DocumentNode, variables?: V): Promise<T> {
  38. const queryString = print(query);
  39. const result = await this.client.rawRequest<T>(queryString, variables);
  40. const authToken = result.headers.get(getConfig().authOptions.authTokenHeaderKey);
  41. if (authToken != null) {
  42. this.setAuthToken(authToken);
  43. }
  44. return result.data as T;
  45. }
  46. async queryStatus<T = any, V = Record<string, any>>(query: DocumentNode, variables?: V): Promise<number> {
  47. const queryString = print(query);
  48. const result = await this.client.rawRequest<T>(queryString, variables);
  49. return result.status;
  50. }
  51. uploadAssets(filePaths: string[]): Promise<any> {
  52. return this.fileUploadMutation({
  53. mutation: CREATE_ASSETS,
  54. filePaths,
  55. mapVariables: fp => ({
  56. input: fp.map(() => ({ file: null })),
  57. }),
  58. });
  59. }
  60. importProducts(csvFilePath: string): Promise<{ importProducts: ImportInfo }> {
  61. return this.fileUploadMutation({
  62. mutation: gql`
  63. mutation ImportProducts($csvFile: Upload!) {
  64. importProducts(csvFile: $csvFile) {
  65. imported
  66. processed
  67. errors
  68. }
  69. }
  70. `,
  71. filePaths: [csvFilePath],
  72. mapVariables: () => ({ csvFile: null }),
  73. });
  74. }
  75. /**
  76. * Uses curl to post a multipart/form-data request to the server. Due to differences between the Node and browser
  77. * environments, we cannot just use an existing library like apollo-upload-client.
  78. *
  79. * Upload spec: https://github.com/jaydenseric/graphql-multipart-request-spec
  80. * Discussion of issue: https://github.com/jaydenseric/apollo-upload-client/issues/32
  81. */
  82. private fileUploadMutation(options: {
  83. mutation: DocumentNode;
  84. filePaths: string[];
  85. mapVariables: (filePaths: string[]) => any;
  86. }): Promise<any> {
  87. const { mutation, filePaths, mapVariables } = options;
  88. return new Promise((resolve, reject) => {
  89. const curl = new Curl();
  90. const postData = createUploadPostData(mutation, filePaths, mapVariables);
  91. const processedPostData = [
  92. {
  93. name: 'operations',
  94. contents: JSON.stringify(postData.operations),
  95. },
  96. {
  97. name: 'map',
  98. contents:
  99. '{' +
  100. Object.entries(postData.map)
  101. .map(([i, path]) => `"${i}":["${path}"]`)
  102. .join(',') +
  103. '}',
  104. },
  105. ...postData.filePaths,
  106. ];
  107. curl.setOpt(Curl.option.URL, this.apiUrl);
  108. curl.setOpt(Curl.option.VERBOSE, false);
  109. curl.setOpt(Curl.option.TIMEOUT_MS, 30000);
  110. curl.setOpt(Curl.option.HTTPPOST, processedPostData);
  111. curl.setOpt(Curl.option.HTTPHEADER, [
  112. `Authorization: Bearer ${this.authToken}`,
  113. `${getConfig().channelTokenKey}: ${this.channelToken}`,
  114. ]);
  115. curl.perform();
  116. curl.on('end', (statusCode: any, body: any) => {
  117. curl.close();
  118. const response = JSON.parse(body);
  119. if (response.errors && response.errors.length) {
  120. const error = response.errors[0];
  121. console.log(JSON.stringify(error.extensions, null, 2));
  122. throw new Error(error.message);
  123. }
  124. resolve(response.data);
  125. });
  126. curl.on('error', (err: any) => {
  127. curl.close();
  128. console.log(err);
  129. reject(err);
  130. });
  131. });
  132. }
  133. async asUserWithCredentials(username: string, password: string) {
  134. // first log out as the current user
  135. if (this.authToken) {
  136. await this.query(
  137. gql`
  138. mutation {
  139. logout
  140. }
  141. `,
  142. );
  143. }
  144. const result = await this.query(
  145. gql`
  146. mutation($username: String!, $password: String!) {
  147. login(username: $username, password: $password) {
  148. user {
  149. id
  150. identifier
  151. channelTokens
  152. }
  153. }
  154. }
  155. `,
  156. {
  157. username,
  158. password,
  159. },
  160. );
  161. return result.login;
  162. }
  163. async asSuperAdmin() {
  164. await this.asUserWithCredentials(SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD);
  165. }
  166. async asAnonymousUser() {
  167. await this.query(
  168. gql`
  169. mutation {
  170. logout
  171. }
  172. `,
  173. );
  174. }
  175. private setHeaders() {
  176. const headers: any = {
  177. [getConfig().channelTokenKey]: this.channelToken,
  178. };
  179. if (this.authToken) {
  180. headers.Authorization = `Bearer ${this.authToken}`;
  181. }
  182. this.client.setHeaders(headers);
  183. }
  184. }