testFlags.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (C) 2012-2023 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. }
  41. } else {
  42. counts[operationFlag] = count + 1
  43. window.testFlags?.set(testFlag)
  44. }
  45. return response
  46. })
  47. })
  48. export default testFlagsLink