api-request.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // @ts-check
  2. import http from 'k6/http';
  3. import { check, fail } from 'k6';
  4. const AUTH_TOKEN_HEADER = 'Vendure-Auth-Token';
  5. export class ApiRequest {
  6. constructor(apiUrl, fileName) {
  7. this.document = open('../graphql/' + fileName);
  8. this.apiUrl = apiUrl;
  9. this.authToken = undefined;
  10. }
  11. /**
  12. * Post the GraphQL request
  13. */
  14. post(variables = {}, authToken) {
  15. const res = http.post(
  16. this.apiUrl,
  17. JSON.stringify({
  18. query: this.document,
  19. variables,
  20. }),
  21. {
  22. timeout: 120 * 1000,
  23. headers: {
  24. Authorization: authToken ? `Bearer ${authToken}` : '',
  25. 'Content-Type': 'application/json',
  26. },
  27. },
  28. );
  29. check(res, {
  30. 'Did not error': r => r.json().errors == null && r.status === 200,
  31. });
  32. const result = res.json();
  33. if (result.errors) {
  34. fail('Errored: ' + result.errors[0].message);
  35. }
  36. if (res.headers[AUTH_TOKEN_HEADER]) {
  37. authToken = res.headers[AUTH_TOKEN_HEADER];
  38. console.log(`Setting auth token: ${authToken}`);
  39. this.authToken = authToken;
  40. }
  41. return res.json();
  42. }
  43. }
  44. export class ShopApiRequest extends ApiRequest {
  45. constructor(fileName) {
  46. super('http://localhost:3000/shop-api/', fileName);
  47. }
  48. }
  49. export class AdminApiRequest extends ApiRequest {
  50. constructor(fileName) {
  51. super('http://localhost:3000/admin-api/', fileName);
  52. }
  53. }