在配置中,我必须指定定义实体的.js和.ts文件的路径:
MikroORM.init({
...
entitiesDirs: ["build/entities"],
entitiesDirsTs: ["src/entities"],
});
因此,何时我要发布或分发该应用程序。我也需要分发打字稿代码吗?还是只需要分配生成的缓存?还是需要同时分发两者?还是...没有?
答案 0 :(得分:1)
现在您可以使用默认的元数据提供程序,仅当您在装饰器中未提供entity
或type
选项时,才需要实体源文件(您可以使用entity
回调来请使用对实体类的引用,而不要在type
中使用字符串名称,而是通过像webstorm这样的IDE进行重构的句柄)。
您也应该发送打字稿代码,并让缓存在服务器上重新生成-无论如何,缓存都会被重建,因为它会检查到缓存实体的绝对路径是否无效。
如果您不想交付打字稿代码,则可以实现自己的缓存适配器或元数据提供程序来解决此问题。
这是实现自定义元数据提供程序的方式,当缺少type选项时,该提供程序只会引发错误:
import { MetadataProvider, Utils } from 'mikro-orm';
import { EntityMetadata } from 'mikro-orm/dist/decorators';
export class SimpleMetadataProvider extends MetadataProvider {
async loadEntityMetadata(meta: EntityMetadata, name: string): Promise<void> {
// init types and column names
Object.values(meta.properties).forEach(prop => {
if (prop.entity) {
prop.type = Utils.className(prop.entity());
} else if (!prop.type) {
throw new Error(`type is missing for ${meta.name}.${prop.name}`)
}
});
}
}
然后在初始化时提供此类:
const orm = await MikroORM.init({
// ...
metadataProvider: SimpleMetadataProvider,
});
type
的值应该是JS类型,例如string/number/Date
...。您可以观察缓存的元数据以确保应该有哪些值。
还要记住,没有TS元数据提供程序,您也需要在@ManyToOne装饰器中指定实体类型(通过entity
回调,或通过type
作为字符串)。