simple-graphql-client.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 gql from 'graphql-tag';
  5. import { print } from 'graphql/language/printer';
  6. import fetch, { Response } from 'node-fetch';
  7. import { Curl } from 'node-libcurl';
  8. import { stringify } from 'querystring';
  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. const LOGIN = gql`
  13. mutation($username: String!, $password: String!) {
  14. login(username: $username, password: $password) {
  15. user {
  16. id
  17. identifier
  18. channelTokens
  19. }
  20. }
  21. }
  22. `;
  23. export type QueryParams = { [key: string]: string | number };
  24. // tslint:disable:no-console
  25. /**
  26. * A minimalistic GraphQL client for populating and querying test data.
  27. */
  28. export class SimpleGraphQLClient {
  29. private authToken: string;
  30. private channelToken: string;
  31. private headers: { [key: string]: any } = {};
  32. constructor(private apiUrl: string = '') {}
  33. setAuthToken(token: string) {
  34. this.authToken = token;
  35. this.headers.Authorization = `Bearer ${this.authToken}`;
  36. }
  37. getAuthToken(): string {
  38. return this.authToken;
  39. }
  40. setChannelToken(token: string) {
  41. this.headers[getConfig().channelTokenKey] = token;
  42. }
  43. /**
  44. * Performs both query and mutation operations.
  45. */
  46. async query<T = any, V = Record<string, any>>(
  47. query: DocumentNode,
  48. variables?: V,
  49. queryParams?: QueryParams,
  50. ): Promise<T> {
  51. const response = await this.request(query, variables, queryParams);
  52. const result = await this.getResult(response);
  53. if (response.ok && !result.errors && result.data) {
  54. return result.data;
  55. } else {
  56. const errorResult = typeof result === 'string' ? { error: result } : result;
  57. throw new ClientError(
  58. { ...errorResult, status: response.status },
  59. { query: print(query), variables },
  60. );
  61. }
  62. }
  63. async queryStatus<T = any, V = Record<string, any>>(query: DocumentNode, variables?: V): Promise<number> {
  64. const response = await this.request(query, variables);
  65. return response.status;
  66. }
  67. importProducts(csvFilePath: string): Promise<{ importProducts: ImportInfo }> {
  68. return this.fileUploadMutation({
  69. mutation: gql`
  70. mutation ImportProducts($csvFile: Upload!) {
  71. importProducts(csvFile: $csvFile) {
  72. imported
  73. processed
  74. errors
  75. }
  76. }
  77. `,
  78. filePaths: [csvFilePath],
  79. mapVariables: () => ({ csvFile: null }),
  80. });
  81. }
  82. async asUserWithCredentials(username: string, password: string) {
  83. // first log out as the current user
  84. if (this.authToken) {
  85. await this.query(
  86. gql`
  87. mutation {
  88. logout
  89. }
  90. `,
  91. );
  92. }
  93. const result = await this.query(LOGIN, { username, password });
  94. return result.login;
  95. }
  96. async asSuperAdmin() {
  97. await this.asUserWithCredentials(SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD);
  98. }
  99. async asAnonymousUser() {
  100. await this.query(
  101. gql`
  102. mutation {
  103. logout
  104. }
  105. `,
  106. );
  107. }
  108. private async request(
  109. query: DocumentNode,
  110. variables?: { [key: string]: any },
  111. queryParams?: QueryParams,
  112. ): Promise<Response> {
  113. const queryString = print(query);
  114. const body = JSON.stringify({
  115. query: queryString,
  116. variables: variables ? variables : undefined,
  117. });
  118. const url = queryParams ? this.apiUrl + `?${stringify(queryParams)}` : this.apiUrl;
  119. const response = await fetch(url, {
  120. method: 'POST',
  121. headers: { 'Content-Type': 'application/json', ...this.headers },
  122. body,
  123. });
  124. const authToken = response.headers.get(getConfig().authOptions.authTokenHeaderKey || '');
  125. if (authToken != null) {
  126. this.setAuthToken(authToken);
  127. }
  128. return response;
  129. }
  130. private async getResult(response: Response): Promise<any> {
  131. const contentType = response.headers.get('Content-Type');
  132. if (contentType && contentType.startsWith('application/json')) {
  133. return response.json();
  134. } else {
  135. return response.text();
  136. }
  137. }
  138. /**
  139. * Uses curl to post a multipart/form-data request to the server. Due to differences between the Node and browser
  140. * environments, we cannot just use an existing library like apollo-upload-client.
  141. *
  142. * Upload spec: https://github.com/jaydenseric/graphql-multipart-request-spec
  143. * Discussion of issue: https://github.com/jaydenseric/apollo-upload-client/issues/32
  144. */
  145. private fileUploadMutation(options: {
  146. mutation: DocumentNode;
  147. filePaths: string[];
  148. mapVariables: (filePaths: string[]) => any;
  149. }): Promise<any> {
  150. const { mutation, filePaths, mapVariables } = options;
  151. return new Promise((resolve, reject) => {
  152. const curl = new Curl();
  153. const postData = createUploadPostData(mutation, filePaths, mapVariables);
  154. const processedPostData = [
  155. {
  156. name: 'operations',
  157. contents: JSON.stringify(postData.operations),
  158. },
  159. {
  160. name: 'map',
  161. contents:
  162. '{' +
  163. Object.entries(postData.map)
  164. .map(([i, path]) => `"${i}":["${path}"]`)
  165. .join(',') +
  166. '}',
  167. },
  168. ...postData.filePaths,
  169. ];
  170. curl.setOpt(Curl.option.URL, this.apiUrl);
  171. curl.setOpt(Curl.option.VERBOSE, false);
  172. curl.setOpt(Curl.option.TIMEOUT_MS, 30000);
  173. curl.setOpt(Curl.option.HTTPPOST, processedPostData);
  174. curl.setOpt(Curl.option.HTTPHEADER, [
  175. `Authorization: Bearer ${this.authToken}`,
  176. `${getConfig().channelTokenKey}: ${this.channelToken}`,
  177. ]);
  178. curl.perform();
  179. curl.on('end', (statusCode: any, body: any) => {
  180. curl.close();
  181. const response = JSON.parse(body);
  182. if (response.errors && response.errors.length) {
  183. const error = response.errors[0];
  184. console.log(JSON.stringify(error.extensions, null, 2));
  185. throw new Error(error.message);
  186. }
  187. resolve(response.data);
  188. });
  189. curl.on('error', (err: any) => {
  190. curl.close();
  191. console.log(err);
  192. reject(err);
  193. });
  194. });
  195. }
  196. }
  197. export class ClientError extends Error {
  198. constructor(public response: any, public request: any) {
  199. super(ClientError.extractMessage(response));
  200. }
  201. private static extractMessage(response: any): string {
  202. if (response.errors) {
  203. return response.errors[0].message;
  204. } else {
  205. return `GraphQL Error (Code: ${response.status})`;
  206. }
  207. }
  208. }