【发布时间】:2021-09-07 20:04:10
【问题描述】:
我正在编写一个通用的解组器。它将图形数据库数据转换为生成的 TypeScript (1.8.7) 模型类。输入是 JSON。输出应该是模型类的实例。
我的最终目标是创建类似 Hibernate OGM 的东西,仅用于 Tinkerpop Frames 和 TypeScript,中间有 REST 端点。
将类作为参数传递并访问它的静态成员的正确方法是什么?我想要这样的东西:
SomeModel some = <SomeModel> unmarshaller.fromJSON({/*Object from JSON*/}, SomeModel);
我试图写一个方法。 不确定我是否朝着正确的方向前进,请随时提出不同的方法。
public fromJSON(input: Object, clazz: typeof FrameModel): FrameModel
{
// This only demonstrates access to Framemodel's metadata
// about original Java model classes.
clazz.graphPropertyMapping;
clazz.graphRelationMapping;
let result = {};
...
return result;
}
...
但是当我尝试在 Plunker 上执行此操作时,我遇到了执行错误,并显示了无用的堆栈跟踪。
模型超类如下所示:
/**
* Things common to all Frames models on the Typescript side.
*/
export class FrameModel
{
// Model metadata
static discriminator: string;
static graphPropertyMapping: { [key:string]:string; };
static graphRelationMapping: { [key:string]:string; };
// Each instance needs a vertex ID
private vertexId: number;
public getVertexId(): number {
return this.vertexId;
}
}
示例模型类:
import {TestPlanetModel} from './TestPlanetModel';
import {TestShipModel} from './TestShipModel';
export class TestGeneratorModel extends FrameModel
{
static discriminator: string = 'TestGenerator';
static graphPropertyMapping: { [key:string]:string; } = {
bar: 'boo',
name: 'name',
rank: 'rank',
};
static graphRelationMapping: { [key:string]:string; } = {
colonizes: 'colonizedPlanet',
commands: 'ship',
};
boo: string;
name: string;
rank: string;
public colonizedPlanet: TestPlanetModel[]; // edge label 'colonizedPlanet'
public ship: TestShipModel; // edge label 'ship'
}
我没有找到太多关于 TypeScript 中反射和类处理的资料。
我知道如何在 Java 中做到这一点。
我知道如何在 JavaScript 中做到这一点。
我知道我可以使用装饰器获得类似的结果,但是对于生成的模型来说,使用字段或静态字段似乎更简单一些。
【问题讨论】:
-
它的常规调用
classklass:)
标签: reflection typescript marshalling unmarshalling