Skip to content

Commit

Permalink
feat: transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
zhenyuWang committed Nov 4, 2023
1 parent 9a2d292 commit 5bc87cd
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/coffees/coffees.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import { CoffeesService } from './coffees.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Coffee } from './entities/coffee.entity';
import { Flavor } from './entities/flavor.entity';
import { Event } from '../events/entities/event.entity/event.entity';

// nest g module 命令行创建 module
// 也可以简写 nest g mo
// 也可以简写 nest g mo moduleName

@Module({
imports: [TypeOrmModule.forFeature([Coffee, Flavor])],
imports: [TypeOrmModule.forFeature([Coffee, Flavor, Event])],
controllers: [CoffeesController],
providers: [CoffeesService],
})
Expand Down
26 changes: 25 additions & 1 deletion src/coffees/coffees.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import { Coffee } from './entities/coffee.entity';
import { CreateCoffeesDto } from './dto/create-coffees.dto/create-coffees.dto';
import { UpdateCoffeesDto } from './dto/update--coffees.dto/update--coffees.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Connection, Repository } from 'typeorm';
import { Flavor } from './entities/flavor.entity';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto/pagination-query.dto';
import { Event } from '../events/entities/event.entity/event.entity';

// nest generate service 命令行创建 controller
// 简写:nest j s
Expand All @@ -22,6 +23,7 @@ export class CoffeesService {
private readonly coffeeRepository: Repository<Coffee>,
@InjectRepository(Flavor)
private readonly flavorRepository: Repository<Flavor>,
private readonly connection: Connection,
) {}

findAll(paginationQuery: PaginationQueryDto) {
Expand Down Expand Up @@ -79,6 +81,28 @@ export class CoffeesService {
return this.coffeeRepository.remove(coffee);
}

async recommendCoffee(coffee: Coffee) {
const queryRunner = this.connection.createQueryRunner();

await queryRunner.connect();
await queryRunner.startTransaction();

try {
coffee.recommendations++;
const recommendEvent = new Event();
recommendEvent.name = 'recommend_coffee';
recommendEvent.type = 'coffee';
recommendEvent.payload = { coffeeId: coffee.id };
await queryRunner.manager.save(coffee);
await queryRunner.manager.save(recommendEvent);
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
}

private async preloadFlavorsByNames(name: string): Promise<Flavor> {
const existFlavor = await this.flavorRepository.findOneBy({ name });
if (existFlavor) {
Expand Down
3 changes: 3 additions & 0 deletions src/coffees/entities/coffee.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export class Coffee {
@Column()
brand: string;

@Column({ default: 0 })
recommendations: number;

// @Column('json', { nullable: true }) // 可选
@JoinTable()
// cascade: true 表示级联保存, 保存coffee的时候, 会级联保存flavor
Expand Down
18 changes: 18 additions & 0 deletions src/events/entities/event.entity/event.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';

@Index(['name', 'type']) // 复合索引
@Entity()
export class Event {
@PrimaryGeneratedColumn()
id: number;

@Column()
type: string;

@Index() // 索引
@Column()
name: string;

@Column('json')
payload: Record<string, any>;
}

0 comments on commit 5bc87cd

Please # to comment.