I’m develop a new server (REST API) with use nodejs and typescript. In the project there is an API folder in which files with classes. These classes are inherited from the API base class. The App class has the initApi method, which loads all the classes on fly from the API folder. Files with API classes are also compiled into *.js. Since they are inherited from the base class Api, they have a static method "isApi".
However, when I try to require compiled files (*.ts -> *.js) with API classes, the entire class definition context is lost, including the parent class.
// Base API class
export default class Api {
public static isApi(): boolean {
return true;
}
}
// Test-API class inherited from API
// Which must be loaded inside App class as a compiled file (*.ts -> *.js)
import Api from "../Api";
export default class TestApi extends Api {
// Just for testing.
public async process() {
return;
}
}
// App class
class App {
...
private initApi() {
const apiRoot = path.join(__dirname, "api");
const walker = walk.walk(apiRoot);
walker.on("file", (root, fileStats, next) => {
// Reg is for JS (generated) files!!!
if (/^[^_].*\.js$/.test(fileStats.name)) {
const apiPath = root.substr(apiRoot.length + 1).replace(/\//g, ".");
const apiName = (apiPath ? apiPath + "." : "") + fileStats.name.substr(0, fileStats.name.length - 3);
const module_ = require(path.join(root, fileStats.name));
// Problem here: module_.isApi and module_.isApi() is undefined.
if (module_.isApi && module_.isApi()) {
this._api[apiName] = module_;
}
next();
}
}
...
}
module_.isApi and module_.isApi() is undefined.
require(), dorequire(...).default