Ond*_*žka 5 reflection marshalling unmarshalling typescript
我正在编写一个通用的解组器。它将图形数据库数据转换为生成的 TypeScript (1.8.7) 模型类。输入是 JSON。输出应该是模型类的实例。
我的最终目标是创建类似 Hibernate OGM 的东西,仅适用于 Tinkerpop Frames 和 TypeScript,中间有 REST 端点。
将类作为参数传递并访问它的静态成员的正确方法是什么?我想要这样的东西:
SomeModel some = <SomeModel> unmarshaller.fromJSON({/*Object from JSON*/}, SomeModel);
Run Code Online (Sandbox Code Playgroud)
我试着写一个方法。不确定我是否朝着正确的方向前进,请随时提出不同的方法。
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;
}
...
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在 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;
}
}
Run Code Online (Sandbox Code Playgroud)
示例模型类:
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'
}
Run Code Online (Sandbox Code Playgroud)
我在 TypeScript 中没有找到太多关于反射和类处理的材料。
我知道我将如何在 Java 中做到这一点。
我知道我将如何在 JavaScript 中做到这一点。
我知道我可能会使用装饰器获得类似的结果,但对于生成的模型,使用字段或静态字段似乎更简单一些。
您可能已经注意到类成员不能有const关键字。但你可以选择去static。如果您希望外部世界可以访问成员,那么成员也应该是公开的。
public static graphPropertyMapping: { [key:string]:string; } = {
bar: 'boo',
name: 'name',
rank: 'rank',
};
Run Code Online (Sandbox Code Playgroud)
至于创建结果实例:
let result = new clazz();
//copy properties
return result;
Run Code Online (Sandbox Code Playgroud)