I need to create an object at runtime and define it's properties. Properties and object itself should be decorated. I need that object to behave the same way as I would define it using class in the source code. Essentially I have dynamic description of a class/object stored in variables.
How can I go from this:
const entityName = 'User'
const entityDecorator = 'Entity'
const entityProperties = [
{ name: "name", type: "string", decorator: { name: 'Column', arguments: [20] } },
{ name: "email", type: "string", decorator: { name: 'Column', arguments: [20, 'email'] } },
]
Object.create({});
// something..
and end up with an object that would behave as it was defined in a normal way in the source code as:
@Entity
export class User {
@Column(20)
name: string
@Column(20, 'email')
email: string
}
I tried this [https://stackoverflow.com/questions/52694469/adding-decorators-to-dynamically-created-functions-in-typescript](Adding decorators to dynamically created functions in typescript) but it didn't help.
It depends on the library and the decorator, but in many cases code like
dynamicClassbelow might work.Unlike the sample input, it requires slightly changing the decorators to be actual decorators and not strings.
Like the sample class in the question, this code does not set the value of the properties and would have to be extended to do so.
It can be used like so: