testFlags.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { ApolloLink } from '@apollo/client/core'
  3. import { getMainDefinition } from '@apollo/client/utilities'
  4. import { Kind } from 'graphql'
  5. const isEmptyResponse = (response: unknown) => {
  6. if (!response) return true
  7. if (Array.isArray(response)) return response.length === 0
  8. if (typeof response === 'object') {
  9. // eslint-disable-next-line no-restricted-syntax
  10. for (const key in response) {
  11. // eslint-disable-next-line no-continue
  12. if (key === '__typename') continue
  13. if ((response as Record<string, string>)[key]) {
  14. return false
  15. }
  16. }
  17. return true
  18. }
  19. return false
  20. }
  21. const counts: Record<string, number> = {}
  22. const testFlagsLink = /* #__PURE__ */ new ApolloLink((operation, forward) => {
  23. return forward(operation).map((response) => {
  24. const definition = getMainDefinition(operation.query)
  25. if (definition.kind === Kind.FRAGMENT_DEFINITION) return response
  26. const operationType = definition.operation
  27. const operationName = definition.name?.value as string
  28. const operationFlag = `__gql ${operationType} ${operationName}`
  29. const count = counts[operationFlag] || 1
  30. const testFlag = `${operationFlag} ${count}`
  31. if (operationType === 'subscription') {
  32. // only trigger subscription, if it was actually returned
  33. // this is also triggered with empty response, when we subscribe
  34. if (
  35. response.errors ||
  36. (response.data && !isEmptyResponse(response.data[operationName]))
  37. ) {
  38. counts[operationFlag] = count + 1
  39. window.testFlags?.set(testFlag)
  40. } else {
  41. window.testFlags?.set(`__gql subscription ${operationName} start`)
  42. }
  43. } else {
  44. counts[operationFlag] = count + 1
  45. window.testFlags?.set(testFlag)
  46. }
  47. return response
  48. })
  49. })
  50. export default testFlagsLink