import { IOrganizationRepository } from '../../../Domain/IRepository/IOrganizationRepository'; import { GetOrganizationsByPageQuery } from './GetOrganizationsByPageQuery'; import { ShortOrganizationDto } from '../../DTOs/OrganizationDto'; import { OrganizationMapper } from '../../DTOs/Mappers/OrganizationMapper'; import { logError, logRequest } from '../../Services/Logger'; export class GetOrganizationsByPageQueryHandler { constructor(private readonly orgRepo: IOrganizationRepository) {} async execute(query: GetOrganizationsByPageQuery): Promise<{ organizations: ShortOrganizationDto[], totalCount: number }> { try { // Validate pagination parameters if (query.from < 0 || query.to < query.from) { throw new Error('Invalid pagination parameters'); } const limit = query.to - query.from + 1; if (limit > 100) { throw new Error('Page size too large. Maximum 100 records per request'); } logRequest('Get organizations by page query started', undefined, undefined, { from: query.from, to: query.to, includeDeleted: query.includeDeleted || false }); const result = query.includeDeleted ? await this.orgRepo.findByPageIncludingDeleted(query.from, query.to) : await this.orgRepo.findByPage(query.from, query.to); logRequest('Get organizations by page query completed', undefined, undefined, { from: query.from, to: query.to, returned: result.organizations.length, totalCount: result.totalCount, includeDeleted: query.includeDeleted || false }); return { organizations: OrganizationMapper.toShortDtoList(result.organizations), totalCount: result.totalCount }; } catch (error) { logError('GetOrganizationsByPageQueryHandler error', error instanceof Error ? error : new Error(String(error))); // Handle database errors if (error instanceof Error && error.message.includes('database')) { throw new Error('Database connection error'); } // Re-throw validation errors as-is if (error instanceof Error && (error.message.includes('Invalid pagination') || error.message.includes('Page size'))) { throw error; } throw new Error('Failed to retrieve organizations'); } } }