Scan Decorated Classes in Typescript

Posted by in Software, Tutorial

TL;DR: Make the decorator set a property in the class and look for it.

While trying my hand at writing an ORM, I had a problem of initialising the database through a dummy instantiation of some models, without running an explicit command. In java, I can use code generation to provide a list of objects following a pattern (e.g. implementing an interface). Here, the concepts are somewhat different and I found out I can use decorators.

My model looks like this:

where the @table() and @field are decorators.

Ideally, I should have a function along the lines:

Now, obtaining the list is somewhat difficult since different classes can be in different files all over the place.

Solution

The solution I found is to have the decorator set an obscure property on the decorated object:

and add it to the @tabledecorator:

Once you have done this, the decorated model will have a property named isSpeciallyDecorated, which we can look for:

Now, all we have to do is invoke the function in the right place:

This will print out that our models are specially decorated.

Note: You need to explicitly import/export the models in your file as the call is only local (this is the current scope).


A little experiment: If you find this post and ad below useful, please check the ad out :-)