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.
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
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With