francescov1 / mongoose-tsgen

A plug-n-play Typescript generator for Mongoose.
105 stars 24 forks source link

Custom Schema Types #163

Open kjkurtz opened 2 months ago

kjkurtz commented 2 months ago

In order to handle Dates where we don't care about the time, we have a custom schema type of DateOnly that is effectively a wrapper around Date with some validators attached to make sure the time is set to midnight UTC via a plugin.

We use a types.d.ts file to make Typescript aware of this additional type which so far has worked. Now, when using mongoose-tsgen, we get an error parser: Unknown type detected for field for any fields using this new custom type.

The type looks like the following:

declare module "mongoose" {
  namespace Schema {
    namespace Types {
      class DateOnly extends Schema.Types.Date {}
    }
  }
}

So quite similar to how you are already augmenting for populate. Any ideas on how to effectively do this so types generate correctly for the schemas that use this custom type? Thanks!

francescov1 commented 2 months ago

Hey @kjkurtz, interesting use case! In general I do want to find ways to make the generated types a bit more extendable. Let me look into this, could you provide a simple repro? Thanks

kjkurtz commented 2 months ago

Sure thing! Here is a basic repo where you can run yarn types and see the parser error that you currently get without having mongoose types augmented. https://github.com/kjkurtz/custom-schema-types

francescov1 commented 1 month ago

Thanks @kjkurtz! So in the current setup in that repo, there isnt any way we can detect that "DateOnly" actually means date, since it doesnt extend from the Mongoose native type mongoose.Schema.Types.Date. I'm not too familiar with custom types like this, but if you can make DateOnly extend from a native Mongoose date type, then I just need a small tweak on my end to detect that.

Trying to do a sort of custom override isnt trivial here unfortunately, it would require a significant overhaul of the current codebase.

francescov1 commented 1 month ago

I did notice a different bug though, the parser thinks that DateOnly is an object, and tries to dig deeper into its subfields. I can push a small fix for this so that it would just be typed as any in the meantime