5. Developing backend code
Now that we have an understanding of both Prisma and NestJS we can start to code our back end. For each of the non relational modules in the Prisma database we need to create the appropriate service and controller files to handle sample HTTP responses.
Our Backend will interact with our front end using HTTP requests and responses. If you look at the main.ts file you will see that our current backend is listening to http//:localhost:3000.
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();Lets start off by implementing the service and controller for the User table. That means, whenever someone sends a HTTP request (e.g., GET()) to the url http//:localhost:3000/user our backend should return the relevant data in format Json.
The first step is to cd to the backend folder and run the command nest g resource user . In the options chose Rest API as the transport layer, and then y to generate CRUD operations. Doing this you should see a new user directory made inside of the src folder. The first step is to delete both entity and dto folders as they will not be need.
user.module.ts
Lets first update the user.module.ts file. Here, we want to import the Database module, so that the userService has access to the Prisma Database. Your updated user.module.ts should look like this:
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { DatabaseModule } from 'src/database/database.module';
@Module({
imports: [DatabaseModule],
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}It is important to notice that when we ran nest g resource user it also added the UserModule to our app.module.ts imports list. The app.module.ts import list should have access to all fundamental modules used that arent directly related to one another (no chain import output).
user.service.ts
Next we will update the user.service.ts file. We need to update all of the created methods to handle the appropriate logic and database operations. All of these methods should have the necessary database queries to either update or gather database data. Section 3 Prisma queries have the list of basic queries that will assist us in updating this file.
First we need to inject the Prisma DatabaseService into this service. After doing this, whenever we write this.db we will have access to our Prisma Database, where we can connect to any of the tables.
Now we will develop the create user method. Replace the CreateUserDto with Prisma.UserCreateInput. When we run prisma generate it creates sample schemas for all basic CRUD methods. Don't forget to make the method asynchronous. Try looking back at all the different Prisma queries to chose the right query to create a user, based on the createUserDto data being sent in. After developing the necessary stems the new create method should look like this:
Next lets do the same thing for the findAll() method. Instead of using the prisma query method create use findMany
Implement the findOne() method, this should look for a unique user based of their id.
Similar to the create method, we are going to have to replace UpdateUserDto with Prisma.UserUpdateInput. Now to handle the logic of updating a user we need to use the update method, which will look for a user based off their id, and update their information with the updateUserDto data. This method should look like this:
Finally implement the code for remove(). It should look like this once complete:
user.controller.ts
As the user.service.ts file handles all the logic behind the database queries we do not need to do much to this file. All we need to do is update the types similar to what we did in user.service. Additionally, we need to inject the user service class into the controller, this is done by adding the constructor. The final updated user.controller.ts file should look like this
Great you have finished all the necessary logic for the user model. Now time for a coding challenge!!!
Coding challenge
Can you do the same thing for the dietary restriction model that is also in our database. By following the same structure as creating the user resource you shouldn't have too much of a difficulty.
In addition to creating the backend code for the dietary restriction are you able to make methods for adding and removing dietary restrictions to users. (HINT, these methods should be found inside of the user.controller and user.service files)
Here is a link to download the necessary extensions and changes. If you are adding these changes to your backend, be sure to add DietaryRestrictionModule to the list of imports inside of your app.module.ts file.
Link to Github with the Finding Nibbles Spike and instructions on how to download new files.
Last updated