9

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
Morten Mertner
  • 9,414
  • 4
  • 39
  • 56
  • I'll add this as related question [generating swagger docs from typescript](https://stackoverflow.com/questions/53570605/generating-swagger-docs-from-typescript-interfaces). Maybe somebody figured out a solution... It'd be really nice to have them all synced automatically. – Adrian Moisa Dec 01 '18 at 13:57

2 Answers2

3

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
};
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
  • Thanks for the suggestion. I actually started with a JSON model with sample data, and derived the interfaces from that. I think the latter is more succinct and easier to maintain, so will probably look for a solution that generates the Mongoose stuff from that. (and apologies for the delay in commenting, work got in the way) – Morten Mertner Dec 21 '12 at 19:12
  • Such a pitty not to have a typescript to schema convertor... Anyway, is there a lib that offers the proposed solution already? – Adrian Moisa Dec 01 '18 at 13:58
  • 1
    Found [typegoose](https://github.com/szokodiakos/typegoose). That solves half the problem :D Still searching for the swagger counterpart. – Adrian Moisa Dec 01 '18 at 14:10
3

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.

Francesco Virga
  • 196
  • 1
  • 10