无法从ctor 参数中获取文件路径信息。它只是一个在某处定义的函数。
基本上,module 和 ctrl 最好在注册时提供给控制器类,因为此时路径是已知的,即:
for (const filename of filenames) {
const Ctrl = require(filename).default;
const [moduleName, ctrlName] = parseCtrlFilename(filename);
Ctrl._module = moduleName;
Ctrl._name = ctrlName;
}
唯一且棘手的解决方法是获取调用Controller 的位置的文件路径。这是通过获取堆栈跟踪来实现的,例如:
const caller = require('caller-callsite');
export function Controller<T extends { new(...args: any[]): {} }> (ctor: T) {
const fullPath = caller().getFileName();
...
}
问题在于它是调用Controller 的路径:
.../foo.ts
@Controller
export class Foo {...}
.../bar.ts
import { Foo } from '.../foo.ts';
// fullPath is still .../foo.ts
export class Bar extends Foo {}
一种更简单但更可靠的方法是从可用的模块中显式提供文件路径:
@Controller(__filename)
export class Foo {...}
有import.meta proposal,即supported by TypeScript。它取决于 Node 项目配置,因为它适用于 esnext 目标:
@Controller(import.meta)
export class Foo {...}
传递给@Controller的import.meta可以作为meta.__dirname使用。