simple-graphql-client.ts 8.3 KB

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