Gathering detailed insights and metrics for @onivoro/server-typeorm-mysql
Gathering detailed insights and metrics for @onivoro/server-typeorm-mysql
Gathering detailed insights and metrics for @onivoro/server-typeorm-mysql
Gathering detailed insights and metrics for @onivoro/server-typeorm-mysql
npm install @onivoro/server-typeorm-mysql
Typescript
Module System
Node Version
NPM Version
TypeScript (76.44%)
HCL (16.96%)
JavaScript (5.33%)
Shell (0.97%)
Dockerfile (0.3%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
85 Commits
1 Branches
1 Contributors
Updated on Jul 11, 2025
Latest Version
24.23.0
Package Id
@onivoro/server-typeorm-mysql@24.23.0
Unpacked Size
64.45 kB
Size
16.06 kB
File Count
63
NPM Version
10.9.3
Node Version
22.16.0
Published on
Jul 11, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
A comprehensive TypeORM MySQL integration library for NestJS applications, providing custom repositories, decorators, utilities, and enhanced MySQL-specific functionality for enterprise-scale database operations.
1npm install @onivoro/server-typeorm-mysql
1import { ServerTypeormMysqlModule } from '@onivoro/server-typeorm-mysql'; 2 3@Module({ 4 imports: [ 5 ServerTypeormMysqlModule.forRoot({ 6 host: 'localhost', 7 port: 3306, 8 username: 'root', 9 password: 'password', 10 database: 'myapp', 11 entities: [User, Product, Order], 12 synchronize: false, 13 logging: true 14 }) 15 ], 16}) 17export class AppModule {}
1import { 2 Table, 3 PrimaryTableColumn, 4 TableColumn, 5 NullableTableColumn 6} from '@onivoro/server-typeorm-mysql'; 7import { Entity } from 'typeorm'; 8 9@Entity() 10@Table('users') 11export class User { 12 @PrimaryTableColumn() 13 id: number; 14 15 @TableColumn({ type: 'varchar', length: 255 }) 16 email: string; 17 18 @TableColumn({ type: 'varchar', length: 100 }) 19 firstName: string; 20 21 @TableColumn({ type: 'varchar', length: 100 }) 22 lastName: string; 23 24 @NullableTableColumn({ type: 'datetime' }) 25 lastLoginAt?: Date; 26 27 @TableColumn({ type: 'boolean', default: true }) 28 isActive: boolean; 29 30 @TableColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' }) 31 createdAt: Date; 32 33 @TableColumn({ 34 type: 'timestamp', 35 default: () => 'CURRENT_TIMESTAMP', 36 onUpdate: 'CURRENT_TIMESTAMP' 37 }) 38 updatedAt: Date; 39}
1import { Injectable } from '@nestjs/common'; 2import { TypeOrmRepository, TypeOrmPagingRepository } from '@onivoro/server-typeorm-mysql'; 3import { EntityManager } from 'typeorm'; 4import { User } from './user.entity'; 5 6@Injectable() 7export class UserRepository extends TypeOrmPagingRepository<User> { 8 constructor(entityManager: EntityManager) { 9 super(User, entityManager); 10 } 11 12 async findByEmail(email: string): Promise<User | null> { 13 return this.getOne({ where: { email } }); 14 } 15 16 async findActiveUsers(): Promise<User[]> { 17 return this.getMany({ where: { isActive: true } }); 18 } 19 20 async findUsersWithPagination(page: number, limit: number) { 21 return this.findWithPaging( 22 { where: { isActive: true } }, 23 { page, limit } 24 ); 25 } 26}
1import { dataSourceConfigFactory } from '@onivoro/server-typeorm-mysql'; 2 3const config = dataSourceConfigFactory({ 4 host: process.env.DB_HOST, 5 port: parseInt(process.env.DB_PORT), 6 username: process.env.DB_USERNAME, 7 password: process.env.DB_PASSWORD, 8 database: process.env.DB_DATABASE, 9 entities: [User, Product, Order], 10 migrations: ['src/migrations/*.ts'], 11 synchronize: false, 12 logging: process.env.NODE_ENV === 'development', 13 ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false 14});
1import { Module } from '@nestjs/common'; 2import { ServerTypeormMysqlModule } from '@onivoro/server-typeorm-mysql'; 3import { ConfigService } from '@nestjs/config'; 4 5@Module({ 6 imports: [ 7 ServerTypeormMysqlModule.forRootAsync({ 8 useFactory: (configService: ConfigService) => ({ 9 host: configService.get('DATABASE_HOST'), 10 port: configService.get('DATABASE_PORT'), 11 username: configService.get('DATABASE_USERNAME'), 12 password: configService.get('DATABASE_PASSWORD'), 13 database: configService.get('DATABASE_NAME'), 14 entities: [__dirname + '/**/*.entity{.ts,.js}'], 15 migrations: [__dirname + '/migrations/*{.ts,.js}'], 16 synchronize: configService.get('NODE_ENV') === 'development', 17 logging: configService.get('DATABASE_LOGGING') === 'true' 18 }), 19 inject: [ConfigService] 20 }) 21 ], 22}) 23export class DatabaseModule {}
1import { Injectable } from '@nestjs/common'; 2import { TypeOrmRepository } from '@onivoro/server-typeorm-mysql'; 3import { EntityManager } from 'typeorm'; 4import { User } from './user.entity'; 5 6@Injectable() 7export class UserRepository extends TypeOrmRepository<User> { 8 constructor(entityManager: EntityManager) { 9 super(User, entityManager); 10 } 11 12 // Create a single user 13 async createUser(userData: Partial<User>): Promise<User> { 14 return this.postOne(userData); 15 } 16 17 // Create multiple users 18 async createUsers(usersData: Partial<User>[]): Promise<User[]> { 19 return this.postMany(usersData); 20 } 21 22 // Find users with filters 23 async findUsers(filters: { isActive?: boolean; email?: string }): Promise<User[]> { 24 return this.getMany({ where: filters }); 25 } 26 27 // Find users with count 28 async findUsersWithCount(filters: { isActive?: boolean }): Promise<[User[], number]> { 29 return this.getManyAndCount({ where: filters }); 30 } 31 32 // Find a single user 33 async findUserById(id: number): Promise<User> { 34 return this.getOne({ where: { id } }); 35 } 36 37 // Update user 38 async updateUser(id: number, updateData: Partial<User>): Promise<void> { 39 await this.patch({ id }, updateData); 40 } 41 42 // Replace user data 43 async replaceUser(id: number, userData: Partial<User>): Promise<void> { 44 await this.put({ id }, userData); 45 } 46 47 // Delete user permanently 48 async deleteUser(id: number): Promise<void> { 49 await this.delete({ id }); 50 } 51 52 // Soft delete user 53 async softDeleteUser(id: number): Promise<void> { 54 await this.softDelete({ id }); 55 } 56}
1import { Injectable } from '@nestjs/common'; 2import { TypeOrmPagingRepository, PageParams, PagedData } from '@onivoro/server-typeorm-mysql'; 3import { EntityManager, Like, Between } from 'typeorm'; 4import { User } from './user.entity'; 5 6@Injectable() 7export class AdvancedUserRepository extends TypeOrmPagingRepository<User> { 8 constructor(entityManager: EntityManager) { 9 super(User, entityManager); 10 } 11 12 async searchUsers( 13 searchTerm: string, 14 pageParams: PageParams 15 ): Promise<PagedData<User>> { 16 const whereConditions = this.buildWhereILike({ 17 firstName: searchTerm, 18 lastName: searchTerm, 19 email: searchTerm 20 }); 21 22 return this.findWithPaging( 23 { 24 where: [ 25 { firstName: Like(`%${searchTerm}%`) }, 26 { lastName: Like(`%${searchTerm}%`) }, 27 { email: Like(`%${searchTerm}%`) } 28 ], 29 order: { createdAt: 'DESC' } 30 }, 31 pageParams 32 ); 33 } 34 35 async findUsersByDateRange( 36 startDate: Date, 37 endDate: Date, 38 pageParams: PageParams 39 ): Promise<PagedData<User>> { 40 return this.findWithPaging( 41 { 42 where: { 43 createdAt: Between(startDate, endDate) 44 }, 45 order: { createdAt: 'DESC' } 46 }, 47 pageParams 48 ); 49 } 50 51 async findRecentlyActiveUsers(days: number = 30): Promise<User[]> { 52 const cutoffDate = new Date(); 53 cutoffDate.setDate(cutoffDate.getDate() - days); 54 55 return this.getMany({ 56 where: { 57 lastLoginAt: Between(cutoffDate, new Date()) 58 }, 59 order: { lastLoginAt: 'DESC' } 60 }); 61 } 62 63 async getUserStatistics(): Promise<{ 64 total: number; 65 active: number; 66 inactive: number; 67 recentlyRegistered: number; 68 }> { 69 const [allUsers, totalCount] = await this.getManyAndCount({}); 70 const [activeUsers, activeCount] = await this.getManyAndCount({ 71 where: { isActive: true } 72 }); 73 const [recentUsers, recentCount] = await this.getManyAndCount({ 74 where: { 75 createdAt: Between( 76 new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7 days ago 77 new Date() 78 ) 79 } 80 }); 81 82 return { 83 total: totalCount, 84 active: activeCount, 85 inactive: totalCount - activeCount, 86 recentlyRegistered: recentCount 87 }; 88 } 89 90 async bulkUpdateUsers( 91 userIds: number[], 92 updateData: Partial<User> 93 ): Promise<void> { 94 for (const id of userIds) { 95 await this.patch({ id }, updateData); 96 } 97 } 98 99 async softDeleteUsers(userIds: number[]): Promise<void> { 100 for (const id of userIds) { 101 await this.softDelete({ id }); 102 } 103 } 104}
1import { 2 Table, 3 PrimaryTableColumn, 4 TableColumn, 5 NullableTableColumn, 6 ManyToOneRelationOptions 7} from '@onivoro/server-typeorm-mysql'; 8import { Entity, ManyToOne, OneToMany, JoinColumn } from 'typeorm'; 9 10@Entity() 11@Table('orders') 12export class Order { 13 @PrimaryTableColumn() 14 id: number; 15 16 @TableColumn({ type: 'varchar', length: 50 }) 17 orderNumber: string; 18 19 @TableColumn({ type: 'decimal', precision: 10, scale: 2 }) 20 totalAmount: number; 21 22 @TableColumn({ type: 'enum', enum: ['pending', 'processing', 'shipped', 'delivered', 'cancelled'] }) 23 status: string; 24 25 @TableColumn({ type: 'int' }) 26 userId: number; 27 28 @TableColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' }) 29 createdAt: Date; 30 31 @NullableTableColumn({ type: 'timestamp' }) 32 shippedAt?: Date; 33 34 @NullableTableColumn({ type: 'timestamp' }) 35 deliveredAt?: Date; 36 37 // Relationships 38 @ManyToOne(() => User, user => user.orders, ManyToOneRelationOptions) 39 @JoinColumn({ name: 'userId' }) 40 user: User; 41 42 @OneToMany(() => OrderItem, orderItem => orderItem.order) 43 items: OrderItem[]; 44} 45 46@Entity() 47@Table('order_items') 48export class OrderItem { 49 @PrimaryTableColumn() 50 id: number; 51 52 @TableColumn({ type: 'int' }) 53 orderId: number; 54 55 @TableColumn({ type: 'int' }) 56 productId: number; 57 58 @TableColumn({ type: 'int' }) 59 quantity: number; 60 61 @TableColumn({ type: 'decimal', precision: 10, scale: 2 }) 62 unitPrice: number; 63 64 @TableColumn({ type: 'decimal', precision: 10, scale: 2 }) 65 totalPrice: number; 66 67 @ManyToOne(() => Order, order => order.items, ManyToOneRelationOptions) 68 @JoinColumn({ name: 'orderId' }) 69 order: Order; 70 71 @ManyToOne(() => Product, product => product.orderItems, ManyToOneRelationOptions) 72 @JoinColumn({ name: 'productId' }) 73 product: Product; 74}
1import { Injectable, NotFoundException } from '@nestjs/common'; 2import { AdvancedUserRepository } from './user.repository'; 3import { User } from './user.entity'; 4import { PageParams, PagedData } from '@onivoro/server-typeorm-mysql'; 5 6@Injectable() 7export class UserService { 8 constructor( 9 private userRepository: AdvancedUserRepository 10 ) {} 11 12 async createUser(userData: Partial<User>): Promise<User> { 13 return this.userRepository.postOne(userData); 14 } 15 16 async findUserById(id: number): Promise<User> { 17 const user = await this.userRepository.getOne({ where: { id } }); 18 if (!user) { 19 throw new NotFoundException(`User with ID ${id} not found`); 20 } 21 return user; 22 } 23 24 async updateUser(id: number, updateData: Partial<User>): Promise<void> { 25 const user = await this.findUserById(id); 26 await this.userRepository.patch({ id }, updateData); 27 } 28 29 async deleteUser(id: number): Promise<void> { 30 const user = await this.findUserById(id); 31 await this.userRepository.softDelete({ id }); 32 } 33 34 async searchUsers( 35 searchTerm: string, 36 pageParams: PageParams 37 ): Promise<PagedData<User>> { 38 return this.userRepository.searchUsers(searchTerm, pageParams); 39 } 40 41 async getUserStatistics() { 42 return this.userRepository.getUserStatistics(); 43 } 44 45 async getRecentlyActiveUsers(days: number = 30): Promise<User[]> { 46 return this.userRepository.findRecentlyActiveUsers(days); 47 } 48 49 async bulkUpdateUsers(userIds: number[], updateData: Partial<User>): Promise<void> { 50 await this.userRepository.bulkUpdateUsers(userIds, updateData); 51 } 52}
1import { Injectable } from '@nestjs/common'; 2import { 3 generateDateQuery, 4 removeFalseyKeys, 5 getSkip, 6 getPagingKey, 7 TypeOrmRepository 8} from '@onivoro/server-typeorm-mysql'; 9import { EntityManager } from 'typeorm'; 10import { Order } from './order.entity'; 11 12@Injectable() 13export class OrderService extends TypeOrmRepository<Order> { 14 constructor(entityManager: EntityManager) { 15 super(Order, entityManager); 16 } 17 18 async findOrdersByDateRange( 19 startDate?: Date, 20 endDate?: Date, 21 status?: string, 22 page: number = 1, 23 limit: number = 10 24 ) { 25 const whereConditions: any = removeFalseyKeys({ 26 status, 27 ...generateDateQuery('createdAt', startDate, endDate) 28 }); 29 30 const skip = getSkip(page, limit); 31 32 const [orders, total] = await this.getManyAndCount({ 33 where: whereConditions, 34 skip, 35 take: limit, 36 order: { createdAt: 'DESC' }, 37 relations: ['user', 'items', 'items.product'] 38 }); 39 40 return { 41 data: orders, 42 pagination: { 43 page, 44 limit, 45 total, 46 pages: Math.ceil(total / limit), 47 key: getPagingKey(page, limit) 48 } 49 }; 50 } 51 52 async getOrderAnalytics(startDate: Date, endDate: Date) { 53 const dateQuery = generateDateQuery('createdAt', startDate, endDate); 54 55 const queryBuilder = this.repo.createQueryBuilder('order') 56 .where(dateQuery); 57 58 const [ 59 totalOrders, 60 totalRevenue, 61 averageOrderValue, 62 statusBreakdown 63 ] = await Promise.all([ 64 queryBuilder.getCount(), 65 queryBuilder 66 .select('SUM(order.totalAmount)', 'total') 67 .getRawOne() 68 .then(result => result.total || 0), 69 queryBuilder 70 .select('AVG(order.totalAmount)', 'average') 71 .getRawOne() 72 .then(result => result.average || 0), 73 queryBuilder 74 .select('order.status', 'status') 75 .addSelect('COUNT(*)', 'count') 76 .groupBy('order.status') 77 .getRawMany() 78 ]); 79 80 return { 81 totalOrders, 82 totalRevenue: parseFloat(totalRevenue), 83 averageOrderValue: parseFloat(averageOrderValue), 84 statusBreakdown: statusBreakdown.reduce((acc, item) => { 85 acc[item.status] = parseInt(item.count); 86 return acc; 87 }, {}) 88 }; 89 } 90}
1import { Injectable } from '@nestjs/common'; 2import { EntityManager } from 'typeorm'; 3import { TypeOrmRepository } from '@onivoro/server-typeorm-mysql'; 4import { User } from './user.entity'; 5import { Order } from './order.entity'; 6import { OrderItem } from './order-item.entity'; 7 8@Injectable() 9export class OrderTransactionService { 10 constructor(private entityManager: EntityManager) {} 11 12 async createOrderWithItems( 13 userId: number, 14 orderData: Partial<Order>, 15 items: Array<{productId: number, quantity: number, unitPrice: number}> 16 ): Promise<Order> { 17 return this.entityManager.transaction(async transactionalEntityManager => { 18 const orderRepo = new TypeOrmRepository<Order>(Order, transactionalEntityManager); 19 const orderItemRepo = new TypeOrmRepository<OrderItem>(OrderItem, transactionalEntityManager); 20 const userRepo = new TypeOrmRepository<User>(User, transactionalEntityManager); 21 22 // Create the order 23 const order = await orderRepo.postOne({ 24 ...orderData, 25 userId, 26 totalAmount: 0 // Will be calculated 27 }); 28 29 // Create order items 30 let totalAmount = 0; 31 const orderItems = []; 32 33 for (const itemData of items) { 34 const totalPrice = itemData.quantity * itemData.unitPrice; 35 totalAmount += totalPrice; 36 37 const orderItem = await orderItemRepo.postOne({ 38 orderId: order.id, 39 productId: itemData.productId, 40 quantity: itemData.quantity, 41 unitPrice: itemData.unitPrice, 42 totalPrice 43 }); 44 45 orderItems.push(orderItem); 46 } 47 48 // Update order total 49 await orderRepo.patch({ id: order.id }, { totalAmount }); 50 51 // Update user's last order date 52 await userRepo.patch({ id: userId }, { 53 updatedAt: new Date() 54 }); 55 56 return order; 57 }); 58 } 59 60 async transferOrderToNewUser( 61 orderId: number, 62 newUserId: number 63 ): Promise<void> { 64 await this.entityManager.transaction(async transactionalEntityManager => { 65 const orderRepo = new TypeOrmRepository<Order>(Order, transactionalEntityManager); 66 67 // Update order 68 await orderRepo.patch({ id: orderId }, { 69 userId: newUserId, 70 updatedAt: new Date() 71 }); 72 73 // Log the transfer using raw query 74 await transactionalEntityManager.query( 75 'INSERT INTO order_transfers (order_id, new_user_id, transferred_at) VALUES (?, ?, ?)', 76 [orderId, newUserId, new Date()] 77 ); 78 }); 79 } 80}
1import { Injectable } from '@nestjs/common'; 2import { TypeOrmRepository } from '@onivoro/server-typeorm-mysql'; 3import { EntityManager, QueryRunner } from 'typeorm'; 4import { User } from './user.entity'; 5import { createWriteStream } from 'fs'; 6 7@Injectable() 8export class UserStreamingService extends TypeOrmRepository<User> { 9 constructor(entityManager: EntityManager) { 10 super(User, entityManager); 11 } 12 13 async exportUsersToFile(filePath: string): Promise<void> { 14 const writeStream = createWriteStream(filePath); 15 16 writeStream.write('id,email,firstName,lastName,createdAt\n'); 17 18 const { stream, error } = await this.queryStream({ 19 query: 'SELECT id, email, firstName, lastName, createdAt FROM users WHERE isActive = 1', 20 onData: async (stream, record: User, count) => { 21 const csvLine = `${record.id},"${record.email}","${record.firstName}","${record.lastName}","${record.createdAt}"\n`; 22 writeStream.write(csvLine); 23 24 if (count % 1000 === 0) { 25 console.log(`Processed ${count} records`); 26 } 27 }, 28 onError: async (stream, error) => { 29 console.error('Stream error:', error); 30 writeStream.end(); 31 }, 32 onEnd: async (stream, count) => { 33 console.log(`Export completed. Total records: ${count}`); 34 writeStream.end(); 35 } 36 }); 37 38 if (error) { 39 throw new Error(`Failed to start streaming: ${error.message}`); 40 } 41 } 42 43 async processLargeDataset(): Promise<void> { 44 const { stream, error } = await this.queryStream({ 45 query: 'SELECT * FROM users WHERE createdAt > DATE_SUB(NOW(), INTERVAL 1 YEAR)', 46 onData: async (stream, record: User, count) => { 47 // Process each record individually 48 // This is memory efficient for large datasets 49 await this.processUserRecord(record); 50 }, 51 onError: async (stream, error) => { 52 console.error('Processing error:', error); 53 }, 54 onEnd: async (stream, count) => { 55 console.log(`Processed ${count} user records`); 56 } 57 }); 58 59 if (error) { 60 throw new Error(`Failed to process dataset: ${error.message}`); 61 } 62 } 63 64 private async processUserRecord(user: User): Promise<void> { 65 // Your custom processing logic here 66 console.log(`Processing user: ${user.email}`); 67 } 68 69 // Static method usage for custom query runners 70 static async streamWithCustomQueryRunner( 71 queryRunner: QueryRunner, 72 query: string 73 ): Promise<void> { 74 const { stream, error } = await TypeOrmRepository.queryStream(queryRunner, { 75 query, 76 onData: async (stream, record, count) => { 77 console.log(`Record ${count}:`, record); 78 }, 79 onEnd: async (stream, count) => { 80 console.log(`Stream completed with ${count} records`); 81 } 82 }); 83 84 if (error) { 85 console.error('Stream failed:', error); 86 } 87 } 88}
Base repository class with enhanced functionality:
1export class TypeOrmRepository<T> { 2 constructor(entityType: any, entityManager: EntityManager) 3 4 // Core CRUD methods 5 async getMany(options: FindManyOptions<T>): Promise<T[]> 6 async getManyAndCount(options: FindManyOptions<T>): Promise<[T[], number]> 7 async getOne(options: FindOneOptions<T>): Promise<T> 8 async postOne(body: Partial<T>): Promise<T> 9 async postMany(body: Partial<T>[]): Promise<T[]> 10 async delete(options: FindOptionsWhere<T>): Promise<void> 11 async softDelete(options: FindOptionsWhere<T>): Promise<void> 12 async put(options: FindOptionsWhere<T>, body: QueryDeepPartialEntity<T>): Promise<void> 13 async patch(options: FindOptionsWhere<T>, body: QueryDeepPartialEntity<T>): Promise<void> 14 15 // Transaction support 16 forTransaction(entityManager: EntityManager): TypeOrmRepository<T> 17 18 // Streaming support 19 async queryStream<TRecord = any>(params: TQueryStreamParams): Promise<{stream: any, error: any}> 20 static async queryStream<TRecord = any>(queryRunner: QueryRunner, params: TQueryStreamParams): Promise<{stream: any, error: any}> 21 22 // Utility methods 23 buildWhereILike(filters?: Record<string, any>): FindOptionsWhere<T> 24 25 // Internal properties 26 get repo(): Repository<T> 27}
Repository with built-in pagination support:
1export class TypeOrmPagingRepository<T> extends TypeOrmRepository<T> { 2 async findWithPaging( 3 options: FindManyOptions<T>, 4 pageParams: PageParams 5 ): Promise<PagedData<T>> 6}
Enhanced table decorator:
1@Table('table_name') 2export class Entity {}
Primary key column decorator:
1@PrimaryTableColumn() 2id: number;
Standard column decorator:
1@TableColumn({ type: 'varchar', length: 255 }) 2name: string;
Nullable column decorator:
1@NullableTableColumn({ type: 'datetime' }) 2deletedAt?: Date;
Create data source configuration:
1function dataSourceConfigFactory(options: DataSourceOptions): DataSourceOptions
Generate date range query conditions:
1function generateDateQuery( 2 field: string, 3 startDate?: Date, 4 endDate?: Date 5): Record<string, any>
Remove falsy values from object:
1function removeFalseyKeys<T>(obj: T): Partial<T>
Pagination parameters:
1interface PageParams { 2 page: number; 3 limit: number; 4}
Paginated response data:
1interface PagedData<T> { 2 data: T[]; 3 pagination: { 4 page: number; 5 limit: number; 6 total: number; 7 pages: number; 8 }; 9}
Query streaming parameters:
1type TQueryStreamParams<TRecord = any> = { 2 query: string; 3 onData?: (stream: ReadStream, record: TRecord, count: number) => Promise<any | void>; 4 onError?: (stream: ReadStream, error: any) => Promise<any | void>; 5 onEnd?: (stream: ReadStream, count: number) => Promise<any | void>; 6};
forTransaction()
method for multi-table operationsqueryStream()
for processing large datasets efficiently1import { Test } from '@nestjs/testing'; 2import { EntityManager } from 'typeorm'; 3import { User } from './user.entity'; 4import { UserService } from './user.service'; 5import { AdvancedUserRepository } from './user.repository'; 6 7describe('UserService', () => { 8 let service: UserService; 9 let repository: AdvancedUserRepository; 10 let entityManager: EntityManager; 11 12 beforeEach(async () => { 13 const mockEntityManager = { 14 getRepository: jest.fn().mockReturnValue({ 15 find: jest.fn(), 16 findAndCount: jest.fn(), 17 findOne: jest.fn(), 18 save: jest.fn(), 19 create: jest.fn(), 20 update: jest.fn(), 21 delete: jest.fn(), 22 softDelete: jest.fn(), 23 createQueryBuilder: jest.fn().mockReturnValue({ 24 insert: jest.fn().mockReturnThis(), 25 values: jest.fn().mockReturnThis(), 26 returning: jest.fn().mockReturnThis(), 27 execute: jest.fn() 28 }) 29 }) 30 }; 31 32 const module = await Test.createTestingModule({ 33 providers: [ 34 UserService, 35 { 36 provide: AdvancedUserRepository, 37 useFactory: () => new AdvancedUserRepository(mockEntityManager as any) 38 }, 39 { 40 provide: EntityManager, 41 useValue: mockEntityManager 42 } 43 ], 44 }).compile(); 45 46 service = module.get<UserService>(UserService); 47 repository = module.get<AdvancedUserRepository>(AdvancedUserRepository); 48 entityManager = module.get<EntityManager>(EntityManager); 49 }); 50 51 it('should create a user', async () => { 52 const userData = { 53 email: 'test@example.com', 54 firstName: 'John', 55 lastName: 'Doe' 56 }; 57 58 const createdUser = { id: 1, ...userData }; 59 jest.spyOn(repository, 'postOne').mockResolvedValue(createdUser as User); 60 61 const result = await service.createUser(userData); 62 expect(result).toEqual(createdUser); 63 }); 64 65 it('should find user by id', async () => { 66 const user = { id: 1, email: 'test@example.com', firstName: 'John', lastName: 'Doe' }; 67 jest.spyOn(repository, 'getOne').mockResolvedValue(user as User); 68 69 const result = await service.findUserById(1); 70 expect(result).toEqual(user); 71 }); 72});
This library is licensed under the MIT License. See the LICENSE file in this package for details.
No vulnerabilities found.
No security vulnerabilities found.