微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Apollo Client 和过滤查询

如何解决Apollo Client 和过滤查询

我正在为观鸟者制作一个应用程序。当观鸟者看到一只鸟时,他们会记录一个sighting我有一个关于所有观鸟者目击事件的提要的查询

import { gql } from "@apollo/client";

export const GET_SIGHTINGS = gql`
  query Sightings($first: Int,$after: String) {
    sightings(first: $first,after: $after) {
      pageInfo {
        endCursor
      }
    edges {
      node {
        id
        location
        note
        seenAt
        mapImage
        images {
          id
          url
        }
        user {
          id
          name
          emoji
        }
        bird {
          id
          commonName
        }
      }
    }
  }
}
`;

这很好用。现在我想为个别观鸟者目击提供单独的饲料。 (此查询在服务器上运行良好):

import { gql } from "@apollo/client";

export const MY_SIGHTINGS = gql`
  query MySightings($first: Int,$after: String,$userId: ID) {
    mySightings: sightings(first: $first,after: $after,userId: $userId) @connection(key: "sightings",filter: ["userId"]) {
      pageInfo {
        endCursor
      }
      edges {
        node {
          id
          location
          note
          seenAt
          mapImage
          images {
            id
            url
          }
          user {
            id
            name
            emoji
          }
          bird {
            id
            commonName
          }
        }
      }
    }
  }
`;

这在第一次运行过滤查询时工作正常,但是一旦呈现主要提要组件,单个提要现在就充满了每个人的目击。如何让缓存在两个查询之间进行区分? @connection 指令听起来像是诀窍,但显然不是

解决方法

我将 Relay Specification 用于我的 API,这意味着我的“集合”是对象而不是数组。这意味着我需要设置特定的类型策略才能使分页工作。不幸的是,这也破坏了 Apollos 对查询参数的自动处理。结果我需要将 userId 添加到我的类型策略的 keyargs 部分:

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        sightings: {
          keyArgs: ["userId"],merge(existing,incoming,{ args }) {
            if (args && !args.after) {
              return incoming;
            }
            if (!existing) {
              return incoming;
            }
            const edges = unionBy("node.__ref",existing.edges,incoming.edges);
            return { ...incoming,edges };
          },},});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。