How to add an query to a GraphQL resolver
#
How to add a query to a GraphQL resolver#
GeneralIn 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
#
ExampleThe example will demonstrate how to add a new query to the resolver class and call a service to execute the query.
#
Adding a new query to user.resolver.ts- 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 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.
#
line-by-line instructionsFollow 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.
#
Check your changesYou 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.
tip
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