tink3rlabs / todo-service

2 stars 0 forks source link

Request Validator using JSON Schema #19

Closed UjwalaK closed 4 months ago

UjwalaK commented 4 months ago

Why gojsonschema over Validator package

  1. JSON schema way of doing request validation is really simple and flexible

  2. JSON schema validator returns error in a nice format, saying what is missing, what type etc ex

    {
    "status": "INVALID_RESOURCE",
    "error": [
    "(root): summary is required",
    "age: Invalid type. Expected: integer, given: string"
    ]
    }

    I did not do any formatting, I am just passing the same error returned by the validator on the other hand, the normal Validator based on type annotation returns errors like

    error 
    Key: 'User.Age' 
    Error:Field validation for 'Age' failed on the 'lte' tag
    Key: 'User.FavouriteColor' 
    Error:Field validation for 'FavouriteColor' failed on the 'iscolor' tag
    Key: 'User.Addresses[0].City' 
    Error:Field validation for 'City' failed

    we need to loop through it and do a little extra formatting

  3. in type annotation we define it as

// User contains user information
type User struct {
    FirstName      string     `validate:"required"`
    LastName       string     `validate:"required"`
    Age            uint8      `validate:"gte=0,lte=130"`
    Email          string     `validate:"required,email"`
    Gender         string     `validate:"oneof=male female prefer_not_to"`
    FavouriteColor string     `validate:"iscolor"`                // alias for 'hexcolor|rgb|rgba|hsl|hsla'
    Addresses      []*Address `validate:"required,dive,required"` // a person can have a home and cottage...
}

I don't see a way of referencing, combining, or picking what we need In JSON schema you can use $ref and allOf and other things to reduce the code