【问题标题】:Apollo Client and filtered queriesApollo 客户端和过滤查询
【发布时间】:2021-06-01 04:13:57
【问题描述】:

我正在为观鸟者制作应用程序。当观鸟者看到一只鸟时,他们会记录一个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 指令听起来像是诀窍,但显然不是

【问题讨论】:

  • 用户过滤应该在服务器上实现 - 当userID 提供时过滤... apollo 已经[应该] 将两个结果保存在单独的键(查询+参数)下... 渲染代码/用法?

标签: javascript graphql apollo apollo-client


【解决方案1】:

我将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 };
          },
        },
      },
    },
  },
});

【讨论】:

    猜你喜欢
    • 2018-05-12
    • 2020-02-15
    • 1970-01-01
    • 2020-11-07
    • 2021-05-17
    • 2018-07-23
    • 2021-03-20
    • 2020-01-23
    • 2019-04-18
    相关资源
    最近更新 更多