简体   繁体   中英

Flattening Result from Apollo/Hasura GraphQL Query using Typescript

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?

A couple suggestions...

  1. Create some transformation logic that flattens the data in memory, ie in the Typescript of your application, use as type assertion.https://www.typescriptlang.org/docs/handbook/interfaces.html .

  2. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM