0
I am using typescript, typeorm, postgres and express; I am trying to start the Teamrepository class created by me through a constructor within the Teamcontroller class, but within the methods that use this class I get that this.teamRepo is undefinded
class TeamController {
private teamRepo: TeamRepository;
constructor() {
const repo = new TypeOrmTeamRepo();
this.teamRepo = new TeamRepository(repo);
// console.log(this.teamRepo) ==> recebo certo
}
public async addTeam(request: Request, response: Response) {
try {
// console.log(this.teamRepo) ==> recebo undefined
const { teamName } = request.body;
const newTeam = await this.teamRepo.create(teamName);
console.log(newTeam);
return response.json(newTeam)
} catch(error) {
console.log(error);
return response.status(404).json(error);
}
}
};
however, if I give console.log() inside the constructor, it returns right, since if I try to give the console.log() inside the method I get Undefined; And for some reason if I create the Teamrepository class outside of Teamcontroller or inside the method, it works correctly, like this:
const teamRepo: IBaseTeamRepo = new TeamRepository(new TypeOrmTeamRepo()); //aqui
class TeamController {
public async addTeam(request: Request, response: Response) {
try {
const teamRepo: IBaseTeamRepo = new TeamRepository(new TypeOrmTeamRepo()); //ou aqui
const { teamName } = request.body;
const newTeam = await teamRepo.create(teamName););
console.log(newTeam);
return response.json(newTeam)
} catch(error) {
console.log(error);
return response.status(404).json(error);
}
}
};
Follow the code of the repositories:
class TeamRepository implements IBaseTeamRepo {
private repository: IBaseTeamRepo;
constructor(repository: IBaseTeamRepo) {
this.repository = repository;
}
public async create(team: BaseTeamModel): Promise<any> {
return await this.repository.create(team);
}
}
export default class TypeOrmTeamRepo implements IBaseTeamRepo {
public async create(newTeamName: string): Promise<any> {
try {
const teamRepo = await getRepository(Team);
console.log(newTeamName);
const newTeam = await teamRepo.create({
teamName: newTeamName
});
await teamRepo.save(newTeam);
return newTeam;
} catch(error) {
return error;
}
}
};
and interfaces:
interface BaseTeamModel {
teamName: string;
};
interface IBaseTeamRepo {
create(BaseTeamModel): Promise<any>;
};
export {
BaseTeamModel,
IBaseTeamRepo,
}
well already tried to pass teamRepo in addTeam function parameters ?
– Lucas Palomo
You say call addTeam with a parameter? , but how do I do that if in router() it has no parameter
– julioHeyDev
Is your project compiling normally? Are classes being exported for external use? How is the controller class used? Even though your question has enough code, it is not possible to produce the error, take a look at [mcve]
– mateusalxd