source

Vuex 대신 Apollo & GraphQL 캐싱을 사용하시겠습니까?

factcode 2023. 7. 8. 11:13
반응형

Vuex 대신 Apollo & GraphQL 캐싱을 사용하시겠습니까?

저는 아폴로 & 그래프QL로 실험하고 있습니다.Vuex를 요구하는 대신 캐쉬를 활용할 수 있다는 것을 읽었습니다. 하지만 두 가지를 결합하는 일종의 안티 패턴을 만들지 않고는 어떻게 해야 할지 고민할 수 없습니다.

그들이 이 상황에 어떻게 접근했는지에 대한 예를 가진 사람이 있습니까?

제가 시도하고 있는 것은:

Vue Apollo의 CLI 설치 사용:

vue add apollo

./vue-apollo.js에서 구성을 설정한 후 공급자 및 기본 옵션에 내보내기를 추가했습니다.

export const defaultOptions = {
  // ...all the default settings
}

export function createProvider (options = {}) {
  // Create apollo client
  const { apolloClient, wsClient } = createApolloClient({
    ...defaultOptions,
    ...options,
  })
  apolloClient.wsClient = wsClient

  // Create vue apollo provider
  const apolloProvider = new VueApollo({
    defaultClient: apolloClient,
    defaultOptions: {
      $query: {
        // fetchPolicy: 'cache-and-network',
      },
    },
    errorHandler (error) {
      // eslint-disable-next-line no-console
      console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
    },
  })

  return apolloProvider
}

./router/index.js에서 아폴로 제공자, 옵션 및 쿼리 가져오기...

import { createProvider, defaultOptions } from '../vue-apollo'
import gql from "graphql-tag"
import homeQuery from '@/queries/home-content.gql'
import pageQuery from '@/queries/page-query.gql'

const client = createProvider(defaultOptions).defaultClient

페이지 쿼리 기능

const loadPage = (to, from, next) => {
  return client.query({
    query: pageQuery,
    variables: {
      slug: to.params.slug
    }
  })
  .then(async ({ data }) => {
    const { pages } = data
    if (!from.name) store.commit('App/setLoadedToTrue') // Adds loader for app's first/initial load

    if (pages.length > 0) {
      const addPageMutation = gql`
        mutation($id: ID!) {
          addPage(id: $id) @client
        }
      `
      await client.mutate({
        mutation: addPageMutation,
        variables: { id: pages[0].id }
      })
      next()
    }
    else next('/')
  })
  .catch(err => {
    console.log(err)
    next('/')
  })
}

홈페이지 내용 조회 기능

const loadHomeData = (to, from, next) => {
  const hasHomeContent = client.cache.data.data['HomePage:1']

  if (hasHomeContent) next() 

  else {
    client.query({ query: homeQuery })
      .then(async () => {
        if (!from.name) store.commit('App/setLoadedToTrue')
        next()
      })
      .catch(err => {
        console.log(err)
        next('/error')
      })
  }
}

각 앞에:

router.beforeEach((to, from, next) => {
  if (!to.hash) NProgress.start()

  if (to.name == 'home') return loadHomeData(to, from, next)
  if (to.name == 'page') return loadPage(to, from, next)

  next()
})

나의 돌연변이와 해결책

export const storePage = gql`
  type page {
    id: ID!,
    title: String!,
    title_highlights: String!,
    image: UploadFile,
    summary: String,
    content_block: [ComponentPageContentBlockPageBlock]
  }

  type Mutation {
    addPageMutation(id: ID!): page
  }
`


export const storeHomePage = gql`
  type homePage {
    id: ID!,
    bg_words: String,
    title: String!,
    highlights: String,
    body: String,
    services: [ComponentHomecontentServices],
    profiles: [ComponentProfilesProfiles],
  }

  type Mutation {
    addHomePageMutation: homePage
  }
`

const resolvers = {
  Mutation: {
    addCaseStudyMutation: (_, ctx, { cache }) => {
      const data = cache.readQuery({ query: storeCaseStudy })
      cache.writeQuery({ query: storeCaseStudy, data })
      return data
    },

    addHomePageMutation: (_, ctx, { cache }) => {
      const data = cache.readQuery({ query: storeHomePage })
      cache.writeQuery({ query: storeHomePage, data })
      return data
    }
  }
}

문의사항

  1. 현재 각 호출에 대해 원격용으로 하나, 로컬용으로 하나, 쿼리에 대해 @client가 있는 로컬용으로 두 개의 쿼리 파일이 있습니다.쿼리 파일을 하나만 가지고 만들 수 있습니까?@client데이터가 존재하는지 여부에 따라 조건부로 제공됩니까?

  2. 읽기 쿼리를 돌연변이와 함께 반환해야 합니까?아니면 제가 근본적으로 그냥addHomePageMutation: (_, ctx, { cache }) => cache.writeQuery({ query: storeHomepage })

  3. 돌연변이를 일으키기 전에 쿼리를 읽어야 합니까?그리고 그 데이터를 기록부에 넘겨야 합니까?쿼리 방법?

  4. 가장 혼란스러운 것은 변수를 전달하지 않고 홈페이지 데이터를 저장하거나 쿼리를 변경하는 것이 혼란스러웠다는 것입니다.결국 저는 그것을 단순히 "쿼리"를 사용하는 것으로 되돌렸습니다. 돌연변이 없이, 하지만 해결책을 제거하지는 않았습니다.그러나 여전히 작동하며, 데이터는 해결 프로그램에 따라 HomePage:id로 캐시되며, 홈페이지는 사용자가 캐시로 돌아갈 때마다 캐시를 참조합니다.이게 어떻게 된 일일까?

  5. 제가 이 코드를 잘못 알고 있는 게 있나요?

vue - 왜 안 되나요useQuery구성 요소에...보통 [반응] ? 라우터를 사용하는 것은 농담처럼 보입니다... 합성할 수 없습니다...어떤 하위 구성 요소가 데이터를 쿼리할 수 있습니까? - 소품 드릴링 방지 패턴?

  1. 현재 각 호출에 대해 원격용으로 하나, 로컬용으로 하나, 쿼리에 대해 @client가 있는 로컬용으로 두 개의 쿼리 파일이 있습니다.데이터가 존재하는지 여부에 따라 하나의 쿼리 파일을 @client 조건부로 만드는 것이 가능합니까?

@클라이언트를 원격 쿼리 결과의 일부(필드)로 사용할 수 있습니다.

  1. 읽기 쿼리를 돌연변이와 함께 반환해야 합니까?아니면 기본적으로 addHomePageMutation: (_, ctx, {cache }) => cache를 사용할 수도 있습니다.writeQuery({query: 저장소)홈페이지 }}

는 어떤 것 - 해야 합니다 -은 단순한 부울 변환정유변의환결합반으로 될 수 . 단순 부울로 정의할 수 있습니다.result필드, 돌연변이가 돌아올 수 있습니다.truevalue.value.value.

  1. 돌연변이를 일으키기 전에 쿼리를 읽어야 합니까?그리고 그 데이터를 기록부에 넘겨야 합니까?쿼리 방법?

아니요, 필수는 아닙니다. 일치하는 구조 데이터만 전달하면 됩니다.

  1. 가장 혼란스러운 것은 변수를 전달하지 않고 홈페이지 데이터를 저장하거나 쿼리를 변경하는 것이 혼란스러웠다는 것입니다.결국 저는 그것을 단순히 "쿼리"를 사용하는 것으로 되돌렸습니다. 돌연변이 없이, 하지만 해결책을 제거하지는 않았습니다.그러나 여전히 작동하며, 데이터는 해결 프로그램에 따라 HomePage:id로 캐시되며, 홈페이지는 사용자가 캐시로 돌아갈 때마다 캐시를 참조합니다.이게 어떻게 된 일일까?

코드가 표시되지 않음, 알 수 없음

  1. 제가 이 코드를 잘못 알고 있는 게 있나요?
  • 로딩 코드는 로컬 해결기에 배치되어야 합니다.
  • 은 야합다니해를 사용해야 .useQuery의 파일

언급URL : https://stackoverflow.com/questions/63125086/using-apollo-graphql-caching-instead-of-vuex

반응형