Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ and a conversion that doesn't fit the field doesn't compile:
* Every error has the translated message, the location (`Tags[1]`, `address.city` with JSON paths), the value, a stable `Code` and named `Params`
* Messages in English, German, Spanish, French and Russian with plural forms, the language of every request from the context, an `Accept-Language` middleware
* `problem`: the errors as `application/problem+json` of RFC 9457 with JSON pointers
* The rules as the keywords of JSON Schema, `vhuma.OpenAPI` puts them into the OpenAPI document of huma: the clients see `maxLength`, `format`, `enum` of the rules
* `github.com/insei/valigo/huma`, `github.com/insei/valigo/gin`, `github.com/insei/valigo/echo`: the rules of valigo in [huma](https://huma.rocks), [gin](https://gin-gonic.com) and [echo](https://echo.labstack.com)

# Performance
Expand Down
105 changes: 105 additions & 0 deletions docs/features/huma.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,108 @@ query.limit - Не может быть больше 100
body.email - Должно быть электронным адресом
body.tags[1] - Должно содержать только латинские буквы и цифры
```

## The rules in the OpenAPI document

`vhuma.OpenAPI(api, v)` returns the OpenAPI document of the api with the rules of valigo in the schemas of the request bodies and their nested structs, by [JSON Schema](schema.md): `maxLength` of `MaxRunes`, `format: email` of `Email`, `items` of `Each`, the required properties of `Required`. Serve it, so the clients and the generators of SDKs see the rules:

```go
mux.HandleFunc("GET /openapi.json", func(w http.ResponseWriter, r *http.Request) {
doc, err := vhuma.OpenAPI(api, validator)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_ = json.NewEncoder(w).Encode(doc)
})
```

with `config.OpenAPIPath = ""` instead of the document of huma, or under another path.

- The schemas of huma are not changed: huma validates the requests by its tags, the rules of valigo are checked in `Resolve` with translated messages, without the duplicates of huma.
- A keyword with another value than the one of the tags of huma, e.g. two `maxLength`, is added to `allOf`: the value must satisfy both.
- The parameters keep the schemas of huma: an operation of huma doesn't know its input type.
- The schemas are found by the registry of huma with the prefix `#/components/schemas/`, the default one.

```go
package main

import (
"context"
"encoding/json"
"fmt"
"net/http"

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/insei/valigo"
vhuma "github.com/insei/valigo/huma"
"github.com/insei/valigo/str"
)

type CreateUserInput struct {
Body struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Tags []string `json:"tags,omitempty"`
}
}

func main() {
validator := valigo.New(valigo.WithFieldLocationNamingFn(vhuma.Location))
valigo.Configure[CreateUserInput](validator, func(b valigo.Configurator[CreateUserInput], i *CreateUserInput) {
b.Field(&i.Body.Name).As(str.Of).MaxRunes(64)
b.Field(&i.Body.Email).As(str.Of).Required().Email()
b.Slice(&i.Body.Tags).As(str.Slice).MaxLen(5).Each(func(tag *str.BaseConfigurator) { tag.Alphanumeric() })
})

api := humago.New(http.NewServeMux(), huma.DefaultConfig("Users", "1.0.0"))
huma.Post(api, "/users", func(context.Context, *CreateUserInput) (*struct{}, error) { return nil, nil })

doc, err := vhuma.OpenAPI(api, validator)
if err != nil {
panic(err)
}
body := doc["components"].(map[string]any)["schemas"].(map[string]any)["CreateUserInputBody"].(map[string]any)
delete(body["properties"].(map[string]any), "$schema") // the property of huma for the link to the schema
out, _ := json.MarshalIndent(body, "", " ")
fmt.Println(string(out))
}
```

Output:

```text
{
"additionalProperties": false,
"properties": {
"email": {
"format": "email",
"minLength": 1,
"type": "string"
},
"name": {
"maxLength": 64,
"type": "string"
},
"tags": {
"items": {
"pattern": "^[a-zA-Z0-9]+$",
"type": "string"
},
"maxItems": 5,
"type": [
"array",
"null"
]
}
},
"required": [
"name",
"email"
],
"type": "object"
}
```

`email` is `omitempty` for huma, `Required` of valigo makes it required in the document; `tags` has the rules of its elements in `items`.
3 changes: 2 additions & 1 deletion docs/features/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ The separate modules for the frameworks.

| Page | What's inside |
|---|---|
| [huma](huma.md) | `github.com/insei/valigo/huma`: the rules in the `Resolve` of huma inputs with the locations of huma |
| [JSON Schema](schema.md) | the rules as the keywords of JSON Schema for the generators of API schemas, `Constraints` |
| [huma](huma.md) | `github.com/insei/valigo/huma`: the rules in the `Resolve` of huma inputs with the locations of huma and in its OpenAPI document |
| [gin](gin.md) | `github.com/insei/valigo/gin`: the `binding.StructValidator` of gin and validation with the language of the request |
| [echo](echo.md) | `github.com/insei/valigo/echo`: the `echo.Validator` and validation with the language of the request |
46 changes: 46 additions & 0 deletions docs/features/schema.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# JSON Schema

The rules that JSON Schema can express are described by its keywords, so the generators of the schemas of an API can show them to the clients: [huma](huma.md#the-rules-in-the-openapi-document) puts them into its OpenAPI document. `v.Constraints()` returns them for other generators.

```go
for _, c := range v.Constraints() {
fmt.Println(c.Struct, c.Field.GetStructPath(), c.Path, c.Keyword, c.Value)
}
```

Every `shared.Constraint` has the configured struct, the field, the path from the schema of the field to the constrained value — `[items]` for the elements of a slice, `[additionalProperties]` for the values of a map, `[propertyNames]` for its keys — the keyword and its value. The keyword `required` means the field is in the required properties of its object.

| Rules | Keywords |
|---|---|
| `str`: `Required` | `required`, `minLength: 1` |
| `str`: `MinRunes`, `MaxRunes`, `MaxLen` | `minLength`, `maxLength` |
| `str`: `Regexp`, `Prefix`, `Suffix`, `Contains`, `Alphanumeric`, `Semver`, `E164`, `HexColor` | `pattern` |
| `str`: `Email`, `URL`, `IPv4`, `IPv6`, `Hostname`, `UUID` | `format`: `email`, `uri`, `ipv4`, `ipv6`, `hostname`, `uuid` |
| `str`: `Datetime(time.RFC3339)`, `Datetime(time.DateOnly)` | `format`: `date-time`, `date` |
| `str`: `Base64`, `Base64URL` | `contentEncoding` |
| `str`, `num`, `uuid`: `AnyOf`; `eq`: `OneOf` | `enum` |
| `eq`: `Equal` | `const` |
| `num`: `Min`, `Max`, `AnyOfInterval`, `Latitude`, `Longitude` | `minimum`, `maximum` |
| `num`, `eq`, `uuid`: `Required` | `required` |
| slices: `Required`, `MinLen`, `MaxLen`, `Unique`, `Each` | `required` and `minItems: 1`, `minItems`, `maxItems`, `uniqueItems`, `items` |
| maps: `Required`, `MinLen`, `MaxLen`, `EachKey`, `EachValue` | `required` and `minProperties: 1`, `minProperties`, `maxProperties`, `propertyNames`, `additionalProperties` |

The schema describes the rules, valigo validates the values: the descriptions are chosen not to be stricter than the rules, so a value valid for valigo is valid for the schema. The formats are annotations of JSON Schema, the validators that check them can differ in details.

- `MinLen` of strings counts bytes, `minLength` counts characters: it isn't described. `MaxLen` is `maxLength`, a string of `n` bytes has no more than `n` characters.
- The rules under `When` of the struct and of fields aren't described, they don't apply to every value.
- After `Trim` and other `Modify` rules only `Required` is described: the schema describes the value of the request, the rules check the modified one.
- Rules on other fields, custom rules and the formats without a keyword of JSON Schema aren't described.

## Your conversions

A [conversion](conversions.md#your-types) describes its rules by `Schema` of the field, `Schema` of a slice configurator describes the rules of the slice:

```go
// Percent checks that the number is in [0, 100].
func (c *RatioConfigurator) Percent() *RatioConfigurator {
c.f.Schema("minimum", 0).Schema("maximum", 100)
c.f.CheckMsg(func(v Ratio) bool { return v >= 0 && v <= 100 }, shared.M("ratio.percent", percentKey))
return c
}
```
129 changes: 129 additions & 0 deletions huma/openapi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package huma

import (
"encoding/json"
"reflect"
"slices"
"strings"

dhuma "github.com/danielgtaylor/huma/v2"
"github.com/insei/fmap/v3"

"github.com/insei/valigo"
"github.com/insei/valigo/shared"
)

// schemasPrefix is the prefix of the references of the schemas of the registry of huma by default.
const schemasPrefix = "#/components/schemas/"

// OpenAPI returns the OpenAPI document of the api as JSON values with the rules of the validator in the schemas
// of the request bodies and their nested structs: maxLength of MaxRunes, minimum of Min, the required properties...,
// see Validator.Constraints. Serve it instead of the document of huma, so the clients see the rules of valigo.
//
// The schemas of huma, which huma validates the requests by, are not changed, the validation stays by valigo
// with translated messages. The parameters keep the schemas of huma.
func OpenAPI(api dhuma.API, v *valigo.Validator) (map[string]any, error) {
oapi := api.OpenAPI()
data, err := json.Marshal(oapi)
if err != nil {
return nil, err
}
var doc map[string]any
_ = json.Unmarshal(data, &doc) // the JSON of json.Marshal
byStruct := map[reflect.Type][]shared.Constraint{}
for _, c := range v.Constraints() {
if owner, ok := ownerOf(c); ok {
byStruct[owner] = append(byStruct[owner], c)
}
}
components, _ := doc["components"].(map[string]any)
schemas, _ := components["schemas"].(map[string]any)
for name, s := range schemas {
constraints := byStruct[oapi.Components.Schemas.TypeFromRef(schemasPrefix+name)]
for _, c := range constraints {
apply(s.(map[string]any), c)
}
}
return doc, nil
}

// ownerOf returns the struct type of the schema the field of the constraint is a property of:
// the configured struct or the nested struct of the field, the embedded structs without a JSON name are flattened.
func ownerOf(c shared.Constraint) (reflect.Type, bool) {
if _, ok := propertyName(c.Field); !ok {
return nil, false
}
owner := c.Field.GetParent()
for owner != nil && owner.GetAnonymous() && jsonName(owner) == "" {
owner = owner.GetParent()
}
if owner == nil {
return c.Struct, true
}
return owner.GetDereferencedType(), true
}

func jsonName(f fmap.Field) string {
name, _, _ := strings.Cut(f.GetTag().Get("json"), ",")
return name
}

// propertyName returns the name of the property of the field in the schema of its struct, false for skipped fields.
func propertyName(f fmap.Field) (string, bool) {
name := jsonName(f)
if name == "-" {
return "", false
}
if name == "" {
name = f.GetName()
}
return name, true
}

// apply adds the constraint to the schema of the struct of its field.
func apply(schema map[string]any, c shared.Constraint) {
name, _ := propertyName(c.Field)
properties, _ := schema["properties"].(map[string]any)
target, ok := properties[name].(map[string]any)
if !ok {
return
}
if c.Keyword == shared.KeywordRequired && len(c.Path) == 0 {
required, _ := schema["required"].([]any)
if !slices.Contains(required, any(name)) {
schema["required"] = append(required, name)
}
return
}
if c.Keyword == shared.KeywordRequired {
// the elements of a slice and the values of a map can't be required
return
}
for _, keyword := range c.Path {
next, ok := target[keyword].(map[string]any)
if !ok {
// additionalProperties: true, or no propertyNames yet
next = map[string]any{}
target[keyword] = next
}
target = next
}
value := normalize(c.Value)
existing, ok := target[c.Keyword]
switch {
case !ok:
target[c.Keyword] = value
case !reflect.DeepEqual(existing, value):
// e.g. two patterns or maxLength of huma and of valigo: the value must satisfy both
allOf, _ := target["allOf"].([]any)
target["allOf"] = append(allOf, map[string]any{c.Keyword: value})
}
}

// normalize converts the value to the JSON values of the document, e.g. ints to float64 and named strings to strings.
func normalize(v any) any {
data, _ := json.Marshal(v) // the values of the constraints are JSON values
var result any
_ = json.Unmarshal(data, &result)
return result
}
Loading
Loading