In this example, you will see how to add a new function with your business logic to an existing service. The entity.service.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 functions, override existing functions that are inherited from entity.service.base, import libraries and modules to the file, or anything else you may need.
You may also use the super keyword to call the functions in the base class.
This example will demonstrate how to pass parameters to the service, how to access the database using prisma client , and how to return the data from the service using your application models.
- Open your application and open the user.service.ts. The file is located in ./server/src/user/user.service.ts.
Initially, the files should look like this
- Add import for User. This is the type that describes the User entity in the application and is required for the return type of our new function.
- Add import for FindOneUserArgs. this is the args type that is used to find a single User by its ID. We will use it as the input parameter of our new function.
- Add the following function at the bottom of the file.
For simplicity and demonstration purposes this function resets a password to a fixed string "123456". It is against best practices to use this function in production as it is. You should instead use a random complex string as the new password.
This function gets an object of type FindOneUserArgs as a parameter. It uses the prisma client to find the user and reset its password and then returns the updated user object.