GollyJer
GollyJer

Reputation: 26732

How to reshape a GraphQL (via Hasura) query response?

I have a CHAT_MESSAGE_FRAGMENT that returns all the message data from my Hasura graphql api.

However, the Gifted Chat react-native component requires the data in a specific structure so I'm attempting to convert it with the query below.

I'm able to alias all the top level data but can't figure out how to add a nested level of data.

I'm guessing it isn't possible but I thought I'd ask in case I'm missing something.

const GIFTED_CHAT_GROUP_MESSAGES_QUERY = gql`
  query chatGroupMessages($chatGroupId: Int!) {
    chat_message(
      where: { to: { id: { _eq: $chatGroupId } } }
    ) {
      _id: id,
      # user: {
      #   _id: from.id,     <== How do I add
      #   name: from.name,  <== this secondary level?
      # },
      text: message,
      image: image_url,
      createdAt: created_at,
      system: message_type,
    }
  }
  ${CHAT_MESSAGE_FRAGMENT}
`;

Upvotes: 0

Views: 939

Answers (2)

Bob T
Bob T

Reputation: 318

Assuming you already have chat_message.user_id -> users.id foreign key constraint set up, you'll also need to alias the from object in addition aliasing any of its nested fields:

const GIFTED_CHAT_GROUP_MESSAGES_QUERY = gql`
  query chatGroupMessages($chatGroupId: Int!) {
    chat_message(
      where: { to: { id: { _eq: $chatGroupId } } }
    ) {
      _id: id,
      from: user: {
        _id: id,
        name
      },
      text: message,
      image: image_url,
      createdAt: created_at,
      system: message_type,
    }
  }
  ${CHAT_MESSAGE_FRAGMENT}
`;

Upvotes: 2

praveenweb
praveenweb

Reputation: 743

The secondary level of data is basically nested object queries in Hasura. You can nest any number of queries as long as a relationship has been created.

In this case, assuming the chat_message table has a user_id field, you can establish a foreign key constraint for chat_message.user_id -> users.id, where users is a table with id as primary key.

Once the foreign key constraint is created, Hasura Console automatically suggests relationships. Here user would be an object relationship in chat_message table.

Here's the official docs link for Creating a relationship

Upvotes: 1

Related Questions