MutationHandler.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import UserError from '#shared/errors/UserError.ts'
  3. import type { UserErrors } from '#shared/types/error.ts'
  4. import type { OperationMutationResult } from '#shared/types/server/apollo/handler.ts'
  5. import BaseHandler from './BaseHandler.ts'
  6. import type { OperationVariables } from '@apollo/client/core'
  7. import type { UseMutationReturn } from '@vue/apollo-composable'
  8. import type { Ref } from 'vue'
  9. export default class MutationHandler<
  10. TResult = OperationMutationResult,
  11. TVariables extends OperationVariables = OperationVariables,
  12. > extends BaseHandler<
  13. TResult,
  14. TVariables,
  15. UseMutationReturn<TResult, TVariables>
  16. > {
  17. public async send(variables?: TVariables): Promise<Maybe<TResult>> {
  18. return new Promise((resolve, reject) => {
  19. this.operationResult.mutate(variables).then((result) => {
  20. if (!result) {
  21. return reject(this.operationError().value)
  22. }
  23. if (result.data) {
  24. const { errors } = Object.values(result.data)[0] as {
  25. errors: UserErrors
  26. }
  27. if (errors) {
  28. const userErrors = new UserError(errors, this.handlerId)
  29. return reject(userErrors)
  30. }
  31. }
  32. return resolve(result.data || null)
  33. })
  34. })
  35. }
  36. public called(): Ref<boolean> {
  37. return this.operationResult.called
  38. }
  39. }