import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { PageOptionsRequestDto } from '~/core/dtos'; import { SetThemeRequestDto } from '../dtos/request'; import { Theme } from '../entities'; import { Junior } from '../entities/junior.entity'; const FIRST_PAGE = 1; @Injectable() export class JuniorRepository { constructor(@InjectRepository(Junior) private juniorRepository: Repository) {} findJuniorsByGuardianId(guardianId: string, pageOptions: PageOptionsRequestDto) { return this.juniorRepository.findAndCount({ where: { guardianId }, relations: ['customer', 'customer.user', 'customer.user.profilePicture'], skip: (pageOptions.page - FIRST_PAGE) * pageOptions.size, take: pageOptions.size, }); } findJuniorById(juniorId: string, withGuardianRelation = false, guardianId?: string) { const relations = ['customer', 'customer.user', 'theme', 'theme.avatar']; if (withGuardianRelation) { relations.push('guardian', 'guardian.customer', 'guardian.customer.user'); } return this.juniorRepository.findOne({ where: { id: juniorId, guardianId }, relations, }); } setTheme(body: SetThemeRequestDto, junior: Junior) { junior.theme = Theme.create({ ...body, junior }); return this.juniorRepository.save(junior); } removeTheme(theme: Theme) { return this.juniorRepository.manager.remove(theme); } findThemeForJunior(juniorId: string) { return this.juniorRepository.manager.findOne(Theme, { where: { juniorId }, relations: ['avatar'] }); } createJunior(userId: string, data: Partial) { return this.juniorRepository.save( this.juniorRepository.create({ id: userId, ...data, }), ); } }