Reputation: 1426
It's common in Nest.JS to see something like this:
@SomeThing({ type: () => MyEntity })
class MyClass {}
What is the purpose of this? It can't be for preventing things from running, as its a class reference, not an instance, and the import is already run. Nor do I think it's lazy loading, as there's no lazy references to it.
So what's the reason for this pattern over, say:
@SomeThing({ type: MyEntity })
class MyClass {}
My objective is, I have a huge list of metadata that has this type
factory as a property and I need the underlying entity it's pointing to. I want to know if there are downsides to calling the function to get the entity
e.g.
const targetClasses = someMetadata.map(meta => meta.targetFn()
Upvotes: 0
Views: 218
Reputation: 70432
It actually is for lazy loading, but not necessarily for the reason you think. It's to ensure that there's no problems when it comes to circular references. If Nest just used type: MyEntity
and MyEntity
imported MyClass
, then one of the two files (or possibly both of them) would have that type
show up as undefined
. By allowing the type to resolve lazily using a factory, it ensures that the type value is there. This also prevents overhead from remembering when to use type: Class
vs type: () => Class
by just unifying the API
Upvotes: 1