Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Mongoose schemas from TypeScript interfaces?

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.

like image 540
Morten Mertner Avatar asked Dec 19 '12 22:12

Morten Mertner


2 Answers

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.

The above would produce something like this in TypeScript:

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

and this in Mongoose:

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

IThing.methods.DoStuff = function (callback) {
    // TODO
};
like image 159
Markus Jarderot Avatar answered Nov 02 '22 05:11

Markus Jarderot


Little late, but we just built a tool to do exactly this, check out mongoose-tsgen. This CLI tool generates an index.d.ts file containing all your schema interfaces, and doesn't require you to rewrite your schemas. Any time you change your schema, just re-run the tool.

like image 33
Francesco Virga Avatar answered Nov 02 '22 04:11

Francesco Virga