从TypeScript界面​​生成Mongoose模式? [英] Generate Mongoose schemas from TypeScript interfaces?

查看:227
本文介绍了从TypeScript界面​​生成Mongoose模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been defining TypeScript interfaces for all of the types and data structures in my app, and will shortly face the task of replicating most of the data structures as Mongoose schema definitions.

我想知道是否有人编写出了一种可以自动生成另一个的解决方案?

I was wondering if not someone has cooked up a solution to auto-generate one from the other?

我想避免维护本质上相同的事物的两个副本的负担.

I'd like to avoid the burden of maintaining two copies of what is essentially the same thing.

推荐答案

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

Easiest would be to use some easy-to-parse format, and generate the Typescript and Mongoose interfaces from that. Here is an example in JSON:

{ "name": "IThing",
  "type": "interface",
  "members": [
      { "name": "SomeProperty",
        "type": "String" },
      { "name": "DoStuff",
        "type": "function",
        "arguments": [
            { "name": "callback",
              "type": "function",
              "arguments": [],
              "return": "Number" }
        ] }
  ] }

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

The structure, and even the markup language can change to what you need.

上面的代码会在TypeScript中产生如下内容:

The above would produce something like this in TypeScript:

interface IThing {
    SomeProperty: String;
    DoStuff(callback: () => Number)
}

和猫鼬中的这个

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

IThing.methods.DoStuff = function (callback) {
    // TODO
};

这篇关于从TypeScript界面​​生成Mongoose模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆