How to implement reverse query in GraphQL API

I have the following schema:

type User {
    id: ID!
    name: String! @search(by: [term])
    follows: [User] 
    ...
}

I want to query users who follow me based on the follows field. I can do this by query ~follows in DQL.

But @reverse does not seem to be supported in GraphQL API yet.

You can do it by using a custom DQL. https://dgraph.io/docs/graphql/custom/graphqlpm/

First, you have to go to Ratel and edit the predicate User.follows to User.follows: [uid] @reverse and then you create the custom DQL.

OR, you could fix the schema and do it all within GraphQL using the @hasInverse

type User {
    id: ID!
    name: String! @search(by: [term])
    follows: [User] 
    hasFollowers: [User] @hasInverse(field: follows)
    ...
}

Note: Adding this to the schema with existing data, does not change the underlying data, so if you have existing data, you would have to manually fix it to get a working solution for past data.

2 Likes

@amaster507 Thanks, this solution is very good.