使用 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
?
最佳答案
一些建议...
创建一些转换逻辑来扁平化内存中的数据,即在应用程序的 Typescript 中,使用
as
类型断言。 https://www.typescriptlang.org/docs/handbook/interfaces.html 。在 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/