Backend Developpement with NextJs Introduction Tutorial

import { Module } from '@nestjs/common';
import { DatabaseModule } from './database/database.module';
import { User } from './users/entities/user.entity';
@Module({
imports: [DatabaseModule.forRoot([User])],
exports: [DatabaseModule],
})
export class ApplicationModule {}
  • controllers to handle the routes
  • providers to fetch data from various places (database, web API)
  • validation within DTO classes
  • authentication verification with guards
  • error handling through Pipes
  • unit tests with .specs.ts files
  • End-to-End tests with .e2e-spec.ts files

Validation DTO / Decorator :

export class CreateUserDto {
@IsString()
@IsOptional()
readonly lastName: string;
@IsString()
@IsOptional()
readonly firstName: string;
@IsPhoneNumber()
readonly phoneNumber: string;
@IsEmail()
readonly email: string;
}
@Post()
async create(@Body() createUserDto: CreateUserDto): Promise<User> {
return await this.service.createUser(createUserDto);
}

NestJs database entities :

  • a service (will be used by the controller)
  • an entity to describe the data we want to fetch/create/update
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
lastName: string;
@Column()
firstName: string;
@Column()
phoneNumber: string;
@Column(unique: true })
email: string;
}
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>
) { }
async createUser(user: User): Promise<User> {
return await this.userRepository.save(user);
}
}
export class User {
id?: number;
firstName: string;
lastName: string;
password: string;
phoneNumber: string;
email: String;
}

Conclusion :

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store