Is it possible for me to get the descriptor for the actual constructor method of a JS class? I am writing my own little wrapper around Express to try and procedurally generate routes and stuff (and I am sure there are plenty of other libraries to do this, but it’s a learning experience).
If I iterate through the function descriptors for a class prototype, I can convert the ‘value’ property to a string that represents a single method. If I call getString() on the descriptor for ‘constructor’ I get the entire class. I ONLY want the body of the constructor. I could add more parsing logic, but there has to be a way to do this.
Here is a simple controller:
const
BaseController = require('../src/baseController');
/**
* Handle requests for the home page
*/
class HomeController extends BaseController {
/**
* @param settings Controller settings
* @param vault Injected vault client
*/
constructor(settings, vault) {
super(settings);
this.vault = vault;
}
/**
* Serve the landing page
* @returns
*/
async get() {
await this.renderAsync({ pageTitle: 'Pechanga Demo' });
}
}
module.exports = HomeController;
Here is what currently comes back for ‘get’:
Object.getOwnPropertyDescriptor(controllerType.prototype, 'get').value.toString()
async get() {
await this.renderAsync('index', { pageTitle: 'Pechanga Demo' });
}
However, getting the descriptor for ‘constructor’ returns the entire class body:
Object.getOwnPropertyDescriptor(controllerType.prototype, 'constructor').value.toString()
I really want is just:
constructor(settings, vault) {
super(settings);
this.vault = vault;
}
Is this possible without parsing the entire class body?