Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
"test:hello": "ts-node ./test.ts"
},
"dependencies": {
"@nestjs-cls/transactional": "^3.1.0",
"@nestjs-cls/transactional-adapter-typeorm": "^1.3.0",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
Expand Down
12 changes: 11 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getDataSourceToken, TypeOrmModule } from '@nestjs/typeorm';
import { TypeOrmConfigService } from './database/typeormConfig.service';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
Expand All @@ -10,6 +10,8 @@ import { OrderDetailModule } from './orderDetail/orderDetail.module';
import { ClsModule } from 'nestjs-cls';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { TransactionInterceptor } from './common/decorator/transaction.decorator';
import { ClsPluginTransactional } from '@nestjs-cls/transactional';
import { TransactionalAdapterTypeOrm } from '@nestjs-cls/transactional-adapter-typeorm';

@Module({
imports: [
Expand All @@ -20,6 +22,14 @@ import { TransactionInterceptor } from './common/decorator/transaction.decorator
ClsModule.forRoot({
global: true,
middleware: { mount: true },
plugins: [
new ClsPluginTransactional({
imports: [TypeOrmModule],
adapter: new TransactionalAdapterTypeOrm({
dataSourceToken: getDataSourceToken(),
}),
}),
],
}),
UserModule,
AuthModule,
Expand Down
13 changes: 8 additions & 5 deletions src/common/entity/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ import {
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import z from 'zod';

export interface IBaseEntity {
id?: number;
createdAt?: Date;
updatedAt?: Date;
}
export const BaseSchema = z.object({
id: z.number().optional(),
createdAt: z.date().optional(),
updatedAt: z.date().optional(),
});

export type IBaseEntity = z.infer<typeof BaseSchema>;

/**
* TypeOrm BaseEntity와 이름중복이 있어서 'My'라는 프리픽스를 사용함
Expand Down
4 changes: 1 addition & 3 deletions src/order/dto/order.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,16 @@ import {
IsString,
Length,
Min,
registerDecorator,
ValidateNested,
ValidationOptions,
} from 'class-validator';
import { IBaseEntity } from '../../common/entity/base';
import { IOrderDetail } from '../../orderDetail/entity/orderDetail.entity';
import { IOrderEntity } from '../entity/order.entity';
import { UserNameVO } from '../../user/vo/name.vo';
import { AddressVO } from '../vo/address.vo';
import { PostalCodeVO } from '../vo/postalCode.vo';
import { IsValidTotalAmount } from '../utils/isValidTotalAmount.decorator';
import { Type } from 'class-transformer';
import { IOrderEntity } from '../entity/order.entity';

type WithoutBaseEntity<T> = Omit<T, keyof IBaseEntity>;

Expand Down
87 changes: 36 additions & 51 deletions src/order/entity/order.entity.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
import {
BaseEntity,
Column,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
} from 'typeorm';
import { IBaseEntity, MyBaseEntity } from '../../common/entity/base';
import { CommonConstraints } from '../../common/entity/base.constraints';
import { UserEntity } from '../../user/entity/user.entity';
import { OrderDetailEntity } from '../../orderDetail/entity/orderDetail.entity';
import z from 'zod';

export const ORDER_STATUS = {
PENDING: 'pending',
Expand All @@ -13,24 +21,23 @@ export const ORDER_STATUS = {
CANCELED: 'canceled',
REFUNDED: 'refunded',
};
const extractOrderStatusEnum = () => Object.values(ORDER_STATUS);
const OrderStatusEnum = extractOrderStatusEnum();
type OrderStatus = typeof ORDER_STATUS;
type TOrderStatus = OrderStatus[keyof OrderStatus];

export interface IOrderEntity extends IBaseEntity {
userId: number;
subtotal: number;
shippingFee: number;
totalAmount: number; // (상품 합계 금액 + 배송비)
orderStatus: TOrderStatus;
recipientName: string;
recipientPhone: string;
shippingAddress: string;
shippingDetailAddress?: string;
postalCode: string;
}

const OrderStatusValues = Object.values(ORDER_STATUS);

const OrderSchema = z.object({
userId: z.number(),
subtotal: z.number(),
shippingFee: z.number(),
totalAmount: z.number(),
orderStatus: z.enum(OrderStatusValues),
recipientName: z.string(),
recipientPhone: z.string(),
shippingAddress: z.string(),
postalCode: z.string(),
shippingDetailAddress: z.string().optional(),
});
type OrderEntityType = z.infer<typeof OrderSchema>;
export type IOrderEntity = IBaseEntity & OrderEntityType;
export type OrderParam = Omit<IOrderEntity, 'orderStatus'>;
export type PersistedOrderEntity = Required<Omit<OrderEntity, 'orderDetails'>>;

@Entity({ name: 'orders' })
Expand All @@ -45,7 +52,7 @@ export class OrderEntity extends MyBaseEntity implements IOrderEntity {
name: 'userId',
referencedColumnName: CommonConstraints.DB_CONSTRAINTS.ID,
})
user: UserEntity;
user?: UserEntity;

@Column({
type: CommonConstraints.DB_CONSTRAINTS.BASIC_NUMBER,
Expand All @@ -67,10 +74,10 @@ export class OrderEntity extends MyBaseEntity implements IOrderEntity {

@Column({
type: 'enum',
enum: OrderStatusEnum,
enum: OrderStatusValues,
default: ORDER_STATUS.PENDING,
})
orderStatus: string;
orderStatus: string = ORDER_STATUS.PENDING;

@Column({
type: CommonConstraints.DB_CONSTRAINTS.BASIC_STRING,
Expand Down Expand Up @@ -99,38 +106,16 @@ export class OrderEntity extends MyBaseEntity implements IOrderEntity {
postalCode: string;

@OneToMany(() => OrderDetailEntity, (orderDetail) => orderDetail.order)
orderDetails: OrderDetailEntity[];
orderDetails?: OrderDetailEntity[];

constructor(param?: IOrderEntity) {
private constructor(param?: IBaseEntity) {
super(param);
if (param) {
const {
orderStatus,
postalCode,
recipientName,
recipientPhone,
shippingAddress,
shippingFee,
subtotal,
totalAmount,
userId,
shippingDetailAddress,
} = param;

this.orderStatus = orderStatus;
this.postalCode = postalCode;
this.recipientName = recipientName;
this.recipientPhone = recipientPhone;
this.shippingAddress = shippingAddress;
this.shippingFee = shippingFee;
this.subtotal = subtotal;
this.totalAmount = totalAmount;
this.userId = userId;
this.shippingDetailAddress = shippingDetailAddress;
}
}

static from(param: IOrderEntity) {
return new OrderEntity(param);
static create(param: OrderParam) {
const safeParsedParam = OrderSchema.parse(param);
const entity = new OrderEntity(param);
Object.assign(entity, safeParsedParam);
return entity;
}
}
2 changes: 1 addition & 1 deletion src/order/entity/orderRequest.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class OrderRequestEntity implements IOrderRequestEntity {
hashedPayload: string;

@Column({ type: 'json' })
responseBody: Record<string, string>;
responseBody: any;

@Column({ type: 'datetime' })
createdAt?: Date;
Expand Down
24 changes: 11 additions & 13 deletions src/order/order.repository.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import { Injectable, NotImplementedException } from '@nestjs/common';
import { OrderEntity } from './entity/order.entity';
import { DataSource } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { BaseRepository } from '../common/repository/base.repository';
import { Injectable } from '@nestjs/common';
import { OrderEntity, PersistedOrderEntity } from './entity/order.entity';
import { TransactionHost } from '@nestjs-cls/transactional';
import { TransactionalAdapterTypeOrm } from '@nestjs-cls/transactional-adapter-typeorm';

@Injectable()
export class OrderRepository extends BaseRepository<OrderEntity> {
export class OrderRepository {
constructor(
protected readonly dataSource: DataSource,
protected readonly clsService: ClsService,
) {
super(clsService, dataSource);
}
private readonly txHost: TransactionHost<TransactionalAdapterTypeOrm>,
) {}

async saveOrder() {
throw new NotImplementedException();
async saveOrder(order: OrderEntity): Promise<PersistedOrderEntity> {
return (await this.txHost.tx
.getRepository(OrderEntity)
.save(order)) as PersistedOrderEntity;
}
}
25 changes: 17 additions & 8 deletions src/order/order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import { OrderRequestService } from './orderRequest.service';
import { ProductPriceService } from '../product/productPrice.service';
import { OrderPolicyService } from './policy/order.policy';
import { OrderRepository } from './order.repository';
import { Transactional } from '../common/decorator/transaction.decorator';
import { ProductService } from '../product/product.service';
import { OrderItemsInput } from './dto/order.dto';
import { Transactional } from '@nestjs-cls/transactional';
import { OrderDto } from './dto/order.dto';
import { OrderEntity, OrderParam } from './entity/order.entity';

@Injectable()
export class OrderService {
Expand Down Expand Up @@ -39,18 +40,26 @@ export class OrderService {
* 2. 재고가 충분하면 재고 감소, 재고가 충분하지 않으면 에러
* 3. 재고가 불충분하면 롤백 및 주문 전체 취소
*/
await this.productService.validateAndDecreaseStocks(orderDto.orderItems);
const { orderItems, ...orderInfos } = orderDto;
await this.productService.validateAndDecreaseStocks(orderItems);

/**
* TODO
* create Order,OrderItems
*/
const result = (await this.orderRepository.saveOrder()) as any; // response
// TODO
// create orderDto

const result = await this.saveOrder(orderInfos, userId);
await this.orderRequestService.save({
id: orderRequestId,
orderDto,
responseBody: result,
userId,
});
}
private async saveOrder(
orderDto: Omit<OrderDto, 'orderItems'>,
userId: number,
) {
const orderParam: OrderParam = { ...orderDto, userId };
const order = OrderEntity.create(orderParam);
return await this.orderRepository.saveOrder(order);
}
}
13 changes: 3 additions & 10 deletions src/product/entity/productPrice.entity.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
import { Column, Entity } from 'typeorm';
import { MyBaseEntity } from '../../common/entity/base';
import { IBaseEntity, MyBaseEntity } from '../../common/entity/base';
import { CommonConstraints } from '../../common/entity/base.constraints';
import { z } from 'zod';

const BaseSchema = z.object({
id: z.number().optional(),
createdAt: z.date().optional(),
updatedAt: z.date().optional(),
});

const ProductPriceSchema = z.object({
productId: z.number(),
price: z.number(),
effectiveDate: z.date(),
isCurrent: z.boolean(),
});

type BaseType = z.infer<typeof BaseSchema>;
type ProductPriceType = z.infer<typeof ProductPriceSchema>;
type IProductPriceEntity = BaseType & ProductPriceType;
type IProductPriceEntity = IBaseEntity & ProductPriceType;
export type PersistedProductPriceEntity = Required<IProductPriceEntity>;

@Entity({ name: 'product_prices' })
Expand Down Expand Up @@ -48,7 +41,7 @@ export class ProductPriceEntity
})
isCurrent: boolean;

private constructor(param?: BaseType) {
private constructor(param?: IBaseEntity) {
super(param);
}

Expand Down
Loading
Loading