Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit 6ee92a5

Browse files
committed
added typeorm and example entity
1 parent 1534a63 commit 6ee92a5

11 files changed

+438
-16
lines changed

nest-cli.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{
22
"collection": "@nestjs/schematics",
3-
"sourceRoot": "src/server"
3+
"sourceRoot": "src/server",
4+
"entryFile": "server/main"
45
}

package.json

+7-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"start": "nest start",
1313
"start:dev": "nest start --watch",
1414
"start:debug": "nest start --debug --watch",
15-
"start:prod": "node dist/main",
15+
"start:prod": "node dist/server/main",
1616
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
1717
"test": "jest",
1818
"test:watch": "jest --watch",
@@ -23,18 +23,22 @@
2323
"dependencies": {
2424
"@emotion/react": "^11.1.4",
2525
"@nestjs/common": "^7.5.1",
26+
"@nestjs/config": "^0.6.1",
2627
"@nestjs/core": "^7.5.1",
2728
"@nestjs/platform-express": "^7.5.1",
2829
"@nestjs/platform-fastify": "^7.6.5",
30+
"@nestjs/typeorm": "^7.1.5",
2931
"@reduxjs/toolkit": "^1.5.0",
32+
"mysql": "^2.18.1",
3033
"next": "^10.0.5",
3134
"next-redux-wrapper": "^6.0.2",
3235
"react": "^17.0.1",
3336
"react-dom": "^17.0.1",
3437
"react-redux": "^7.2.2",
3538
"reflect-metadata": "^0.1.13",
3639
"rimraf": "^3.0.2",
37-
"rxjs": "^6.6.3"
40+
"rxjs": "^6.6.3",
41+
"typeorm": "^0.2.30"
3842
},
3943
"devDependencies": {
4044
"@babel/core": "^7.12.10",
@@ -117,4 +121,4 @@
117121
"resolutions": {
118122
"webpack": "^5.4.0"
119123
}
120-
}
124+
}

src/server/app.module.ts

+26-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,32 @@
11
import { Module } from '@nestjs/common';
2-
import { ViewMdodule } from './modules/view/view.module';
2+
import { ConfigModule, ConfigService } from '@nestjs/config';
3+
import { TypeOrmModule } from '@nestjs/typeorm';
4+
import { ViewMdodule } from '~server/modules/view/view.module';
5+
import { UsersModule } from '~server/modules/user/users.module';
36

47
@Module({
5-
imports: [ViewMdodule],
8+
imports: [
9+
TypeOrmModule.forRootAsync({
10+
imports: [
11+
ConfigModule.forRoot({
12+
envFilePath: '.env.mysql.local',
13+
}),
14+
],
15+
useFactory: (configService: ConfigService) => ({
16+
type: 'mysql',
17+
host: configService.get('MYSQL_HOST') || 'localhost',
18+
port: configService.get<number>('MYSQL_PORT') || 3306,
19+
username: configService.get('MYSQL_USERNAME'),
20+
password: configService.get('MYSQL_PASSWORD'),
21+
database: configService.get('MYSQL_DATABASE'),
22+
entities: [`${__dirname}/**/*.entity.{ts,js}`],
23+
synchronize: true,
24+
}),
25+
inject: [ConfigService],
26+
}),
27+
UsersModule,
28+
ViewMdodule,
29+
],
630
controllers: [],
731
providers: [],
832
})

src/server/main.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
async function bootstrap() {
99
const app = await NestFactory.create<NestFastifyApplication>(
1010
AppModule,
11-
new FastifyAdapter(),
11+
new FastifyAdapter()
1212
);
1313
await app.listen(3000);
1414
}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
2+
3+
@Entity()
4+
export class User {
5+
@PrimaryGeneratedColumn()
6+
id: number;
7+
8+
@Column()
9+
firstName: string;
10+
11+
@Column()
12+
lastName: string;
13+
14+
@Column({ default: true })
15+
isActive: boolean;
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
2+
import { User } from './user.entity';
3+
import { UsersService } from './users.service';
4+
5+
@Controller('users')
6+
export class UsersController {
7+
constructor(private readonly usersService: UsersService) {}
8+
9+
@Post()
10+
create(@Body() body: Pick<User, 'firstName' | 'lastName'>) {
11+
return this.usersService.create(body);
12+
}
13+
14+
@Get()
15+
findAll() {
16+
return this.usersService.findAll();
17+
}
18+
19+
@Get(':id')
20+
findOne(@Param('id') id: string) {
21+
return this.usersService.findOne(id);
22+
}
23+
24+
@Delete(':id')
25+
remove(@Param('id') id: string) {
26+
return this.usersService.remove(id);
27+
}
28+
}
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { Module } from '@nestjs/common';
2+
import { TypeOrmModule } from '@nestjs/typeorm';
3+
import { UsersController } from './users.controller';
4+
import { UsersService } from './users.service';
5+
import { User } from './user.entity';
6+
7+
@Module({
8+
imports: [TypeOrmModule.forFeature([User])],
9+
providers: [UsersService],
10+
controllers: [UsersController],
11+
})
12+
export class UsersModule {}
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { Injectable } from '@nestjs/common';
2+
import { EntityManager } from 'typeorm';
3+
import { InjectEntityManager } from '@nestjs/typeorm';
4+
import { User } from './user.entity';
5+
6+
// TypeORM transaction pattern
7+
// https://docs.nestjs.com/techniques/database#transactions
8+
// can use other patterns as well
9+
@Injectable()
10+
export class UsersService {
11+
constructor(
12+
@InjectEntityManager()
13+
private readonly entityManager: EntityManager
14+
) {}
15+
16+
findAll() {
17+
return this.entityManager.find(User);
18+
}
19+
20+
findOne(id: string) {
21+
return this.entityManager.findOne(User, id);
22+
}
23+
24+
async remove(id: string) {
25+
await this.entityManager.delete(User, id);
26+
}
27+
28+
create(userName: Pick<User, 'firstName' | 'lastName'>) {
29+
const user = new User();
30+
user.firstName = userName.firstName;
31+
user.lastName = userName.lastName;
32+
return this.entityManager.save(user);
33+
}
34+
35+
async createMany(users: User[]) {
36+
for (let i = 0; i < users.length; i += 1) {
37+
await this.entityManager.save(users[i]);
38+
}
39+
}
40+
}

src/server/modules/view/view.controller.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {} from '@nestjs/platform-fastify';
33
import { ViewService } from './view.service';
44
import { FastifyRequest, FastifyReply } from 'fastify';
55

6-
@Controller('/')
6+
@Controller()
77
export class ViewController {
88
constructor(private viewService: ViewService) {}
99

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { Connection, QueryRunner } from 'typeorm';
2+
3+
class QueryRunnerFactory {
4+
private readonly queryRunner: QueryRunner;
5+
constructor(connection: Connection) {
6+
this.queryRunner = connection.createQueryRunner();
7+
this.queryRunner.connect();
8+
}
9+
10+
async getTransactionManager() {
11+
await this.queryRunner.startTransaction();
12+
return this.queryRunner.manager;
13+
}
14+
15+
async commitTransaction() {
16+
try {
17+
await this.queryRunner.commitTransaction();
18+
} catch (err) {
19+
await this.queryRunner.rollbackTransaction();
20+
}
21+
}
22+
23+
async release() {
24+
await this.queryRunner.release();
25+
}
26+
}
27+
28+
export default QueryRunnerFactory;

0 commit comments

Comments
 (0)