vega / ts-json-schema-generator

Generate JSON schema from your Typescript sources
MIT License
1.44k stars 190 forks source link

Any way to indicate that a string is actually a date-time? #1992

Closed mikesnare closed 3 months ago

mikesnare commented 3 months ago

I'm using this to generate a schema from types used to model AWS EventBridge events. The events have a number of strings that are most correctly modeled with a format of date-time. However, because they're strings in the types they're just being modeled as simple strings in the schema. That makes perfect sense.

But...

It would be nice if it were possible to somehow hint to ts-json-schema-generator that the string is actually a date-time. I'm not interested in converting the strings into Dates when I ingest them from event bridge, so changing the type isn't really an option. Is there anything that can be done here?

Thanks!

domoritz commented 3 months ago

Can you describe how that should look like in the schema? It may already be possible.

mikesnare commented 3 months ago

@domoritz It would just be a string type with a format of date-string:

      "properties": {
        "awarded_at": {
          "type": "string"
          "format": "date-time"
        }
      },

The problem here is that in my TS file, the awarded_at property is typed as a simple string, not a Date.

domoritz commented 3 months ago

Don't we have support for format already?

mikesnare commented 3 months ago

Yes, but only if the type of the property in the TS file is a Date. In my case it's a string. It happens to be a string that is an iso-8601 date-time and I'd like to be able to have that fact reflected in the schema.

mikesnare commented 3 months ago

Example with comments that illustrates the point:

export class Whatever {
  /**
   * This is a string, but it happens to be an ISO-8601 encoded time.   I don't want to have to go
   * through the trouble of parsing this into an actual Date instance when it comes off the wire.
   * I want to leave it as a string to keep the marshaling code simple.  But it would be nice if
   * there were a way for me to annotate this property somehow to tell ts-json-schema-generator
   * that, while this is "just" a string, it should use the date-time format in the schema.
   */
  aDateString: string;
}
janruo commented 3 months ago
export class Whatever {
  /** @format date-time */
  aDateString: string;
}

This seems to be the way.

I don't even remember how I figured this out myself, because it is undocumented. Supported tags can be found in the source: https://github.com/vega/ts-json-schema-generator/blob/next/src/AnnotationsReader/BasicAnnotationsReader.ts

mikesnare commented 3 months ago

Beautiful. Honestly, I can't believe I didn't just try that. Thanks!