Storing typeorm repository function in a variable and calling doesn't works

259 Views Asked by At

I have a typeorm repository function called findOne in a repository called SampleRepository. I am using nestJS and injected the SampleRepository object in the service class. We can invoke that function like

function sample(){
    this.sampleRepository.findOne(// relevant code)
}

But, when we store that function reference in a variable and use that variable to call findOne, it's throwing an error Cannot read properties of undefined (reading 'manager')

    const ref = this.sampleRepository.findOne;
    ref(// relevant code)

I understand this seems so weird and mindless. But, it's happening. Is there any other parsing happens or am I missing something?

1

There are 1 best solutions below

0
Jay McDoniel On BEST ANSWER

I believe the issue here is that the context for the this of the findOne is being lost. I think you'd need to do const ref = this.sampleRepository.findOne.bind(this.sampleRepository) so that later when you call ref() you have the proper context. The other option is just don't set the method to a variable reference