Reputation: 3697
Using Apollo client hooks, I retrieve the following query in a component:
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
}
}
`;
How can I make the result coming back from Hasura map to my User
interface correctly, effectively flattening organization_users.user
above?
Upvotes: 0
Views: 1405
Reputation: 11
Adding another suggestion here to avimoondra's answer:
Computed Fields
with Hasura computed fields you can actually avoid having to make an entirely new view to create this. You can actually just make role
a virtual property of the user schema by defining a function on the user object which returns the role.
See more here: https://hasura.io/docs/1.0/graphql/manual/schema/computed-fields.html
Upvotes: 0
Reputation: 896
A couple suggestions...
Create some transformation logic that flattens the data in memory, i.e. in the Typescript of your application, use as
type assertion. https://www.typescriptlang.org/docs/handbook/interfaces.html.
create a view in Hasura that combines the user
columns and organization_users
columns. So organization_users_view
may be defined as
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;
So the query then looks like...
export const GET_USERS = gql `
query GetUsers {
organization_users_view {
id
email
role
}
}
`;
Which is closer with less code, but double check you retain the benefits of Apollo cache in hydrating other parts of your application, which heavily depends on id and resource "type". It also requires some overhead of defining and/or modifying the view every time you need more columns (can use, users.* and organization_users.* as needed). A benefit, however, is that this will play nicely with type and component generation... so you don't have to define the interface by hand.
Upvotes: 1