In this example, you will see how to add a query to a GraphQL resolver.
The entity.resolver.ts file is generated only once by Amplication, and you can freely customize it. Amplication will never override this file.
You can use this file to add new queries and mutations or override existing ones that are inherited from entity.resolver.base.ts
The example will demonstrate how to add a new query to the resolver class and call a service to execute the query.
- Open the file user.resolver.ts. The file is located in ./server/src/user/user.resolver.ts.
Initially, the file should look like this
- Add import for gqlUserRoles. This is the decorator that provides the roles of the current user.
- Add import for UserFindManyArgs. this is the args type that is used to find multiple Users. We will use it as the input parameter of our new function.
- Add the following code at the bottom of the class.
The above code overrides the default users query. It adds a value to the take property to limit the number of users to return.
Follow this line-by-line explanation to learn more about the code you used:
This decorator defines that this function is a GraphQL query with a return type Array of User.
This decorator Uses nestJS Access Control to enforce access permissions based on the user's role permissions. This example validates that the current user can read user records.
Create a function called users. with parameter of type FindManyUserArgs and return type User.
Create a permission object to be used later for result filtering based on the user permissions.
Call the user service to execute the findMany function, then check and filter the results before returning them to the client.
You are ready to check your changes. Just save all changes and restart your server. Navigate to http://localhost:3000/graphql/ to see and execute the new query.
You can run your server in watch mode so it automatically restarts every time a file in the server code is changed. Instead of using npm start you should use this command