从TypeScript接口生成Mongoose模式?

Mor*_*ner 5 mongoose typescript

我一直在为我的应用程序中的所有类型和数据结构定义TypeScript接口,并且很快将面临将大多数数据结构复制为Mongoose模式定义的任务.

我想知道是否有人已经制定了一个解决方案来自动生成一个来自另一个?

我想避免维护两份本质上相同的东西的负担.

Mar*_*rot 3

最简单的方法是使用一些易于解析的格式,并从中生成 Typescript 和 Mongoose 接口。以下是 JSON 格式的示例:

{ "name": "IThing",
  "type": "interface",
  "members": [
      { "name": "SomeProperty",
        "type": "String" },
      { "name": "DoStuff",
        "type": "function",
        "arguments": [
            { "name": "callback",
              "type": "function",
              "arguments": [],
              "return": "Number" }
        ] }
  ] }
Run Code Online (Sandbox Code Playgroud)

结构,甚至标记语言都可以更改为您需要的内容。

上面的代码在 TypeScript 中会产生类似这样的结果:

interface IThing {
    SomeProperty: String;
    DoStuff(callback: () => Number)
}
Run Code Online (Sandbox Code Playgroud)

在猫鼬中:

var IThing = new Schema({
    "SomeProperty": "String"
});

IThing.methods.DoStuff = function (callback) {
    // TODO
};
Run Code Online (Sandbox Code Playgroud)