Skip to content

custom TypeORM @InjectRepository #1569

@Evanion

Description

@Evanion

Since the extension library uses APIs that are deprecated for a long time, and I couldn't get them to work, I tried to implement my own.

import { type EntityTarget, type ObjectLiteral } from "typeorm";
import { appDataSource } from "../data-source";
import { Constructable, Container } from "typedi";

export function InjectRepository(
  entity: EntityTarget<ObjectLiteral>
): ParameterDecorator {
  return (object, propertyName, index): void => {

    Container.registerHandler({
      object: object as Constructable<unknown>,
      propertyName: propertyName as string,
      index,
      value: () => {
        const repo = appDataSource.getRepository(entity)},
        console.log('injecting', repo);
        return repo;
    });
  };
}

The console.log in the decorator correctly logs out the repository,
But when I log it out in the service that consumes it:

@Service()
export class PersonaService {
  constructor(@InjectRepository(Persona) private personaRepo: Repository<Persona>){}

  getPersona(id:string){
    console.log('repo', this.personaRepo)
    return this.personaRepo.findOneBy({id});
  }
}

It logs out a ContainerInstance rather than the repo.

ContainerInstance {
  services: [
    {
      id: [Token],
      type: null,
      factory: undefined,
      value: [DataSource],
      global: false,
      multiple: false,
      eager: false,
      transient: false
    },
    {
      id: [Token],
      type: [class PersonaService],
      factory: undefined,
      value: [PersonaService],
      global: false,
      multiple: false,
      eager: false,
      transient: false
    },
    {
      id: [Token],
      type: [class AuthService],
      factory: undefined,
      value: [AuthService],
      global: false,
      multiple: false,
      eager: false,
      transient: false
    }
  ],
  id: 'default'
}

and a TypeError: TypeError: this.personaRepo.findOneBy is not a function

I don't understand what I'm doing wrong.

Package.json:

{
  "dependencies": {
      "typedi": "^0.10.0",
      "typeorm": "^0.3.25",
      "typeorm-typedi-extensions": "^0.4.1"
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions