nest.js TypeORM Database
https://medium.com/@shaibenshimol/nestjs-and-mysql-in-10-minutes-711e02ec1dab
ormconfig.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "root",
"database": "my_nestjs_project",
"entities": ["src/**/**.entity{.ts,.js}"],
"synchronize": true,
"extra": { connectionLimit: 10, ... }
}
Very Important !!
app.module
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot(),
UsersModule
],
})
export class AppModule {}
=====nest command can use or not=====
nest g module users
nest g service users
nest g controller users
nest g class users/user.entity
Use TypeORM Active Record
https://github.com/typeorm/typeorm/blob/master/docs/active-record-data-mapper.md
user.entity.ts
import {BaseEntity, Entity, PrimaryGeneratedColumn, Column} from "typeorm";
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
isActive: boolean;
static findByName(firstName: string, lastName: string) {
return this.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName })
.andWhere("user.lastName = :lastName", { lastName })
.getMany();
}
}
How to use
import { User } from './user.entity';
const timber = await User.findByName("Timber", "Saw");
===== Use Other way ====
Users module
app.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot(),
UsersModule
],
})
export class AppModule {}
users.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UsersService],
controllers: [UsersController],
})
export class UsersModule { }
users.controller.ts
import { Controller, Post, Body, Get, Put, Delete,Param} from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from './user.entity';
@Controller('users')
export class UsersController {
constructor(private service: UsersService) { }
@Get(':id')
get(@Param() params) {
return this.service.getUser(params.id);
//return timber = await User.findByName("Timber", "Saw");
}
@Post()
create(@Body() user: User) {
return this.service.createUser(user);
}
@Put()
update(@Body() user: User) {
return this.service.updateUser(user);
}
@Delete(':id')
deleteUser(@Param() params) {
return this.service.deleteUser(params.id);
}
}
users.service.ts This file maybe don’t need because use Active Record.
import { Injectable, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user-entity';
@Injectable()
export class UsersService {
constructor(@InjectRepository(User) private usersRepository: Repository) { }
async getUsers(user: User): Promise {
return await this.usersRepository.find();
}
async getUser(_id: number): Promise {
return await this.usersRepository.find({
select: ["fullName", "birthday", "isActive"],
where: [{ "id": _id }]
});
}
async updateUser(user: User) {
this.usersRepository.save(user)
}
async deleteUser(user: User) {
this.usersRepository.delete(user);
}
}
https://blog.entrostat.com/setting-up-a-database-module-in-nest-js/