typeorm 事务用法

789 阅读1分钟

按在 typeorm 手册上的事务教程,使用的 Connection, getConnection, getMannager 方法。框架都提示已经删除。

image.png

所以改用 Repository库下的事务方法

try {
            const addRes = await this.componentRepository.manager.transaction(
                async (transactionRepository) => {
                        // 保存元件信息
                        let component = new Component();
                        componentData.faeId = componentData.employeeId;
                        componentData.customerChoose = CustomerToNum(componentData.customerChoose);
                        // 厂牌
                        let brand = await this.brandRepository.findOne({where: {id: componentData.brandId}})
                        componentData.brand = brand;
                        // 料号
                        let partNo = await this.partNoRepository.findOne({where: {id: componentData.partNoId}})
                        componentData.partNo = partNo;
                        // 方案信息
                        let info = await this.infoRepository.findOne({where: {id: componentData.projectInfoId}})
                        componentData.info = info;
                        component = componentData;
                        await transactionRepository.save(Component, component);
                        let statusDate = new ComponentStatusDate();
                        statusDate.component = component;
                        statusDate.promotionDate = componentData.promotionDate;
                        statusDate.dinDate = componentData.dinDate;
                        statusDate.samplerunDate = componentData.samplerunDate;
                        statusDate.pilotrunDate = componentData.pilotrunDate;
                        statusDate.mpDate = componentData.mpDate;
                        // 保存草稿箱
                        const res = await transactionRepository.save(ComponentStatusDate,statusDate);
                        return res;
                    }
                );
            console.log("Transaction completed successfully.");
            return addRes;
        } catch (error) {
            console.log("Transaction failed:", error);
            throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }

由于 typeorm 资料较少,所以就记录分享下 Repository 库下的事务方法的使用