usePagination.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, reactive, readonly, ref } from 'vue'
  3. import type { OperationVariables } from '@apollo/client/core'
  4. import type { QueryHandler } from '@shared/server/apollo/handler'
  5. import type {
  6. BaseConnection,
  7. OperationQueryResult,
  8. PaginationVariables,
  9. } from '@shared/types/server/apollo/handler'
  10. export default function usePagination<
  11. TQueryResult = OperationQueryResult,
  12. TQueryVariables = OperationVariables,
  13. >(query: QueryHandler<TQueryResult, TQueryVariables>, resultKey: string) {
  14. const pageInfo = computed(() => {
  15. const result: OperationQueryResult = query.result().value || {}
  16. return (result[resultKey] as BaseConnection)?.pageInfo
  17. })
  18. const hasNextPage = computed(() => {
  19. return pageInfo.value?.hasNextPage ?? false
  20. })
  21. const hasPreviousPage = computed(() => {
  22. return pageInfo.value?.hasPreviousPage ?? false
  23. })
  24. const loadingNewPage = ref(false)
  25. return reactive({
  26. pageInfo: readonly(pageInfo),
  27. hasNextPage: readonly(hasNextPage),
  28. hasPreviousPage: readonly(hasPreviousPage),
  29. loadingNewPage: readonly(loadingNewPage),
  30. async fetchPreviousPage() {
  31. try {
  32. loadingNewPage.value = true
  33. await query.fetchMore({
  34. variables: {
  35. cursor: pageInfo.value?.startCursor,
  36. } as Partial<TQueryVariables & PaginationVariables>,
  37. })
  38. } finally {
  39. loadingNewPage.value = false
  40. }
  41. },
  42. async fetchNextPage() {
  43. try {
  44. loadingNewPage.value = true
  45. await query.fetchMore({
  46. variables: {
  47. cursor: pageInfo.value?.endCursor,
  48. } as Partial<TQueryVariables & PaginationVariables>,
  49. })
  50. } finally {
  51. loadingNewPage.value = false
  52. }
  53. },
  54. })
  55. }