In this example, you will see how to add an action to a REST API controller.
The entity.controller.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 actions (endpoints) or override existing actions that are inherited from entity.controller.base
The example will demonstrate how to get the parameters from the request and call a service to execute the operation.
It will also demonstrate how to check the user's permissions, how to add Swagger UI documentation, and how to log the request.
- Open the file user.controller.ts. The file is located in ./server/src/user/user.controller.ts.
Initially, the files should look like this
- Add the following code at the bottom of the class.
The above code gets a user ID from the request, checks for the user permissions, and calls the user service to reset the password.
Follow this line-by-line explanation to learn more about the code you used:
This decorator instructs morgan to log every request to this endpoint. This line is optional.
This decorator instructs nestJS to guard this endpoint and prevent anonymous access.
This decorator sets the route for the endpoint.
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 update user records.
These 3 decorators provide information for Swagger UI documentation
Create a function called resetPassword with parameter of type UserWhereUniqueInput and return type User | null.
This line creates a parameter named userRoles and extract its value from the current context using nestAccessControl. UserWhereUniqueInput and return type User | null.
Create a permission object to be used later for result filtering based on the user permissions.
Call the user service to execute the resetPassword, 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/api/ to see and execute the new API endpoint.
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