simple-graphql-client.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '@vendure/common/lib/shared-constants';
  2. import { VendureConfig } from '@vendure/core';
  3. import FormData from 'form-data';
  4. import fs from 'fs';
  5. import { DocumentNode } from 'graphql';
  6. import gql from 'graphql-tag';
  7. import { print } from 'graphql/language/printer';
  8. import fetch, { RequestInit, Response } from 'node-fetch';
  9. import { stringify } from 'querystring';
  10. import { QueryParams } from './types';
  11. import { createUploadPostData } from './utils/create-upload-post-data';
  12. const LOGIN = gql`
  13. mutation($username: String!, $password: String!) {
  14. login(username: $username, password: $password) {
  15. ... on CurrentUser {
  16. id
  17. identifier
  18. channels {
  19. token
  20. }
  21. }
  22. ... on ErrorResult {
  23. errorCode
  24. message
  25. }
  26. }
  27. }
  28. `;
  29. // tslint:disable:no-console
  30. /**
  31. * @description
  32. * A minimalistic GraphQL client for populating and querying test data.
  33. *
  34. * @docsCategory testing
  35. */
  36. export class SimpleGraphQLClient {
  37. private authToken: string;
  38. private channelToken: string | null = null;
  39. private headers: { [key: string]: any } = {};
  40. constructor(private vendureConfig: Required<VendureConfig>, private apiUrl: string = '') {}
  41. /**
  42. * @description
  43. * Sets the authToken to be used in each GraphQL request.
  44. */
  45. setAuthToken(token: string) {
  46. this.authToken = token;
  47. this.headers.Authorization = `Bearer ${this.authToken}`;
  48. }
  49. /**
  50. * @description
  51. * Sets the authToken to be used in each GraphQL request.
  52. */
  53. setChannelToken(token: string | null) {
  54. this.channelToken = token;
  55. if (this.vendureConfig.apiOptions.channelTokenKey) {
  56. this.headers[this.vendureConfig.apiOptions.channelTokenKey] = this.channelToken;
  57. }
  58. }
  59. /**
  60. * @description
  61. * Returns the authToken currently being used.
  62. */
  63. getAuthToken(): string {
  64. return this.authToken;
  65. }
  66. /**
  67. * @description
  68. * Performs both query and mutation operations.
  69. */
  70. async query<T = any, V = Record<string, any>>(
  71. query: DocumentNode,
  72. variables?: V,
  73. queryParams?: QueryParams,
  74. ): Promise<T> {
  75. const response = await this.makeGraphQlRequest(query, variables, queryParams);
  76. const result = await this.getResult(response);
  77. if (response.ok && !result.errors && result.data) {
  78. return result.data;
  79. } else {
  80. const errorResult = typeof result === 'string' ? { error: result } : result;
  81. throw new ClientError(
  82. { ...errorResult, status: response.status },
  83. { query: print(query), variables },
  84. );
  85. }
  86. }
  87. /**
  88. * @description
  89. * Performs a raw HTTP request to the given URL, but also includes the authToken & channelToken
  90. * headers if they have been set. Useful for testing non-GraphQL endpoints, e.g. for plugins
  91. * which make use of REST controllers.
  92. */
  93. async fetch(url: string, options: RequestInit = {}): Promise<Response> {
  94. const headers = { 'Content-Type': 'application/json', ...this.headers, ...options.headers };
  95. const response = await fetch(url, {
  96. ...options,
  97. headers,
  98. });
  99. const authToken = response.headers.get(this.vendureConfig.authOptions.authTokenHeaderKey || '');
  100. if (authToken != null) {
  101. this.setAuthToken(authToken);
  102. }
  103. return response;
  104. }
  105. /**
  106. * @description
  107. * Performs a query or mutation and returns the resulting status code.
  108. */
  109. async queryStatus<T = any, V = Record<string, any>>(query: DocumentNode, variables?: V): Promise<number> {
  110. const response = await this.makeGraphQlRequest(query, variables);
  111. return response.status;
  112. }
  113. /**
  114. * @description
  115. * Attemps to log in with the specified credentials.
  116. */
  117. async asUserWithCredentials(username: string, password: string) {
  118. // first log out as the current user
  119. if (this.authToken) {
  120. await this.query(
  121. gql`
  122. mutation {
  123. logout {
  124. success
  125. }
  126. }
  127. `,
  128. );
  129. }
  130. const result = await this.query(LOGIN, { username, password });
  131. if (result.login.channels?.length === 1) {
  132. this.setChannelToken(result.login.channels[0].token);
  133. }
  134. return result.login;
  135. }
  136. /**
  137. * @description
  138. * Logs in as the SuperAdmin user.
  139. */
  140. async asSuperAdmin() {
  141. const { superadminCredentials } = this.vendureConfig.authOptions;
  142. await this.asUserWithCredentials(
  143. superadminCredentials?.identifier ?? SUPER_ADMIN_USER_IDENTIFIER,
  144. superadminCredentials?.password ?? SUPER_ADMIN_USER_PASSWORD,
  145. );
  146. }
  147. /**
  148. * @description
  149. * Logs out so that the client is then treated as an anonymous user.
  150. */
  151. async asAnonymousUser() {
  152. await this.query(
  153. gql`
  154. mutation {
  155. logout {
  156. success
  157. }
  158. }
  159. `,
  160. );
  161. }
  162. private async makeGraphQlRequest(
  163. query: DocumentNode,
  164. variables?: { [key: string]: any },
  165. queryParams?: QueryParams,
  166. ): Promise<Response> {
  167. const queryString = print(query);
  168. const body = JSON.stringify({
  169. query: queryString,
  170. variables: variables ? variables : undefined,
  171. });
  172. const url = queryParams ? this.apiUrl + `?${stringify(queryParams)}` : this.apiUrl;
  173. return this.fetch(url, {
  174. method: 'POST',
  175. body,
  176. });
  177. }
  178. private async getResult(response: Response): Promise<any> {
  179. const contentType = response.headers.get('Content-Type');
  180. if (contentType && contentType.startsWith('application/json')) {
  181. return response.json();
  182. } else {
  183. return response.text();
  184. }
  185. }
  186. /**
  187. * @description
  188. * Perform a file upload mutation.
  189. *
  190. * Upload spec: https://github.com/jaydenseric/graphql-multipart-request-spec
  191. * Discussion of issue: https://github.com/jaydenseric/apollo-upload-client/issues/32
  192. */
  193. async fileUploadMutation(options: {
  194. mutation: DocumentNode;
  195. filePaths: string[];
  196. mapVariables: (filePaths: string[]) => any;
  197. }): Promise<any> {
  198. const { mutation, filePaths, mapVariables } = options;
  199. const postData = createUploadPostData(mutation, filePaths, mapVariables);
  200. const body = new FormData();
  201. body.append('operations', JSON.stringify(postData.operations));
  202. body.append(
  203. 'map',
  204. '{' +
  205. Object.entries(postData.map)
  206. .map(([i, path]) => `"${i}":["${path}"]`)
  207. .join(',') +
  208. '}',
  209. );
  210. for (const filePath of postData.filePaths) {
  211. const file = fs.readFileSync(filePath.file);
  212. body.append(filePath.name, file, { filename: filePath.file });
  213. }
  214. const result = await fetch(this.apiUrl, {
  215. method: 'POST',
  216. body,
  217. headers: {
  218. ...this.headers,
  219. },
  220. });
  221. const response = await result.json();
  222. if (response.errors && response.errors.length) {
  223. const error = response.errors[0];
  224. throw new Error(error.message);
  225. }
  226. return response.data;
  227. }
  228. }
  229. export class ClientError extends Error {
  230. constructor(public response: any, public request: any) {
  231. super(ClientError.extractMessage(response));
  232. }
  233. private static extractMessage(response: any): string {
  234. if (response.errors) {
  235. return response.errors[0].message;
  236. } else {
  237. return `GraphQL Error (Code: ${response.status})`;
  238. }
  239. }
  240. }