问题描述
客观
我有三个表,分别为clients
,contacts
和telephones
。如果通过一个client.id
,我有一种方法可以根据contact.id
或client.id
退回所有电话,我希望能同时退还与此client
的所有电话到contacts
。但是这没有用。我通过client.id
返回了我所有的电话,但如果contact.id
返回了一个空数组。如果我更改了if位置,请给我contacts
个电话,但client
个电话是空的。
序列
telephones.routes.ts
telephonesRouter.get('/:id',telephonesController.index);
TelephonesController.ts
public async index(request: Request,response: Response): Promise<Response> {
const { id } = request.params;
try {
const telephoneService = container.resolve(GetTelephoneService);
const telephones = await telephoneService.execute({ id });
return response.status(200).json({ telephones });
} catch (err) {
return response.status(400).json({ error: err.message });
}
}
GetTelephoneService.ts
import { injectable,inject } from 'tsyringe';
import AppError from '@shared/errors/AppError';
/* Interface */
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
import IContactsRepository from '@modules/contacts/repositories/IContactsRepository';
import ITelephonesRepository from '../repositories/ITelephonesRepository';
import Telephone from '../infra/typeorm/entities/Telephone';
interface IRequest {
id: string;
}
@injectable()
class GetTelephoneService {
constructor(
@inject('TelephonesRepository')
private telephonesRepository: ITelephonesRepository,@inject('ClientsRepository')
private clientsRepository: IClientsRepository,@inject('ContactsRepository')
private contactsRepository: IContactsRepository,) {}
public async execute({ id }: IRequest): Promise<Telephone[] | undefined> {
const isContact = await this.contactsRepository.findContact(id);
if (isContact !== undefined) {
const telephones = await this.telephonesRepository.getAllTelephones(id);
return telephones;
}
const isClient = await this.clientsRepository.findClient(id);
if (isClient !== undefined) {
const telephones = await this.telephonesRepository.getAllTelephones(id);
return telephones;
}
if (!isContact && !isClient) {
throw new AppError("We can't found the id",400);
}
return undefined;
}
}
export default GetTelephoneService;
TelephonesRepository.ts
public async getAllTelephones(
owner_id: string,): Promise<Telephone[] | undefined> {
const getTelephoneClient = await this.ormRepository.find({
where: { client_id: owner_id },});
console.log('getTelephoneClient',getTelephoneClient);
const getTelephoneContact = await this.ormRepository.find({
where: { contact_id: owner_id,client_id: null },});
console.log('getTelephoneContact',getTelephoneContact);
if (getTelephoneClient !== undefined) {
return getTelephoneClient;
}
if (getTelephoneContact !== undefined) {
return getTelephoneContact;
}
return undefined;
}
如果在TelephonesRepository.ts
,我首先通过getTelephoneClient
。将返回客户拥有的电话。但是,如果我通过contact.id
,则getTelephoneContact
将为空。如果我反转,请反转行为。
解决方法
我所做的解决方案是在if's
处,我看到它们永远不会是undefined
,它们将包含data
或将是一个空数组,因为返回值始终为{{1 }}。因此,我验证了Telephone[] | undefined
的长度是否不同于0。