| | | |

How to Create Query for Getting User by ID in Graphql || Nestjs + Typeorm

In this blog, we will discuss how to make a query to fetch one user by id. This’s very simple. We only gonna modify 2 files, user.service and user.resolvers

  1. user.service
  2. user.resolver

user.service

We’ll make one function with just one line of code. The code is simply finding our expected user in our database. With Typeform, the code will basically look like:
<your-user-repository>.find({where: {id: <inputedID>}});

This is our example of the complete function:

async findOne(id: number): Promise<User> {
 return await this.userRepository.findOne({ where: { _id: id } });  
}

user.resolver

In resolvers, we were just gonna take the input and pass it to the function that we just created.
The query that we created pretty much like the code below:

@Query(returns => User)
async findUser(@Args({name: 'id', type: () => ID}) id: string): Promise {
return await this.usersService.findOne(parseInt(id));
}

To that, our query is created. See also the demonstration on a video of how to create a query of get one user below:

Similar Posts