glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
12.51k stars 1.09k forks source link

JS/TS validation of common restrictions (minimum, minLength, pattern, etc.) #1316

Open callumlocke opened 5 years ago

callumlocke commented 5 years ago

Take this example JSON Schema, with integers restricted to certain ranges:

{
  "$id": "https://example.com/geographical-location.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Longitude and Latitude Values",
  "description": "A geographical coordinate.",
  "required": [ "latitude", "longitude" ],
  "type": "object",
  "properties": {
    "latitude": {
      "type": "number",
      "minimum": -90,
      "maximum": 90
    },
    "longitude": {
      "type": "number",
      "minimum": -180,
      "maximum": 180
    }
  }
}

Currently, if you use quicktype to generate JavaScript or TypeScript from the above, the generated runtime validation functions only enforce that latitude and longitude are numbers.

It would be great if they could also enforce the minimum, maximum and other restrictions.

Here's a non-exhaustive list of restrictions I believe are not currently enforced by generated validation functions (gathered from this site):


For the case of generated TypeScript definitions, it might make sense to generate opaque types to represent restricted types, as well as safe casting functions. Something like:

// helper
type Opaque<K, T> = T & { __opaque__: K };

export type Latitude = Opaque<'Latitude', number>;

export interface LatLon {
    latitude:  Latitude;
    longitude: Longitude;
}

// ...plus:
function castAsLatitude(num: number): Latitude {
    if (num < -90 || num > 90) invalidValue(num, 'Latitude');
    return num as Latitude;
}
kdisneur commented 4 years ago

Hi!

I just found this library because we would like to generate some Go code from our JSON-Schema. This feature is exactly what is missing from all the JSON-Schema -> Code converters we found.

I was wondering if you already planned to add this in your roadmap and if we could somehow help you to make this one happen. 🙂

Thanks

jasonkolodziej commented 4 years ago

Same here!!!!

gpodila-disc commented 4 years ago

+1 addition to what mentioned above, Im looking for unique values in array.