javascript - 使用 Typescript 展平来自 Apollo/Hasura GraphQL 查询的结果

标签 javascript typescript react-apollo apollo-client hasura

使用 Apollo 客户端 Hook ,我在组件中检索以下查询:

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

interface User {
  id: number;
  email: string;
  role: string;
}

interface QueryData {
  organization_users: OrgUser[];
}

export const GET_USERS = gql `
  query GetUsers {
    organization_users {
      user {
        id
        email
      }
      role
    }
  }
`;

如何才能使结果从 Hasura map 正确返回到我的User 界面,从而有效地扁平化上面的 organization_users.user

最佳答案

一些建议...

  1. 创建一些转换逻辑来扁平化内存中的数据,即在应用程序的 Typescript 中,使用 as 类型断言。 https://www.typescriptlang.org/docs/handbook/interfaces.html

  2. 在 Hasura 中创建一个组合了 user 列和 organization_users 列的 View 。因此organization_users_view可以定义为

select user.id as id, users.email as email, organization_users.role as role
  from organization_users 
  join users 
  on organization_users.user_id = users.id;

所以查询看起来像......

export const GET_USERS = gql `
  query GetUsers {
    organization_users_view {
      id
      email
      role
    }
  }
`;

这与更少的代码更接近,但请仔细检查您是否保留了 Apollo 缓存在滋润应用程序其他部分方面的优势,这在很大程度上取决于 id 和资源“类型”。每次需要更多列时,还需要一些定义和/或修改 View 的开销(可以根据需要使用 users.* 和organization_users.*)。然而,一个好处是,这可以很好地处理类型和组件生成...因此您不必手动定义接口(interface)。

关于javascript - 使用 Typescript 展平来自 Apollo/Hasura GraphQL 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60814393/

相关文章:

javascript - bxSlider - 播放/暂停页面上的所有 slider

typescript - 在 typescript 中获取类的键

forms - TimePicker 返回对象不是时间 Angular 4

javascript - Apollo useLazyQuery 监听完成

graphql - 如何在一个请求中使用不同的参数多次运行一个突变?

javascript - 我如何用 Jest 配置jsdom

javascript - TypeScript 组织 : namespaces? 模块?困惑

graphql - 如何将嵌套变量传递给 Apollo 中的 GraphQL 查询?

javascript - Raphael js,如何获取圆心的x、y位置?

typescript - 如何将 TypeScript 构造函数参数属性与类继承和父类(super class)构造函数结合起来?