swaggest / jsonschema-go

JSON Schema mapping for Go
https://pkg.go.dev/github.com/swaggest/jsonschema-go
MIT License
123 stars 14 forks source link

Any chance to have access to the actual values of a types while implementing interfaces? #66

Closed tpoxa closed 1 year ago

tpoxa commented 1 year ago
type Condition struct {
  Param bool

}

func (d Condition) JSONSchema() (jsonschema.Schema, error) {
  //custom logic based on d.Param
  return jsonschema.Schema{}, nil
}

schema, _ := reflector.Reflect(Condition{Param:true})

Will I get an access to the real value of Param in the implementation? I this example it should be true

Thanks.

vearutop commented 1 year ago

Yeah, you don't need to do anything special for that, just supply a sample with values.

package main

import (
    "encoding/json"
    "fmt"
    "github.com/swaggest/jsonschema-go"
)

type S1 struct {
    A int `json:"a"`
    S S2  `json:"s"`
}

type S2 struct {
    B string `json:"b"`
}

func (s S2) JSONSchema() (jsonschema.Schema, error) {
    schema := jsonschema.Schema{}
    schema.AddType(jsonschema.Boolean)

    schema.WithDescription(s.B)

    return schema, nil
}

func main() {
    r := jsonschema.Reflector{}
    s, _ := r.Reflect(S1{S: S2{B: "test"}})
    j, _ := json.MarshalIndent(s, "", " ")

    fmt.Println(string(j))
}
{
 "definitions": {
  "S2": {
   "description": "test",
   "type": "boolean"
  }
 },
 "properties": {
  "a": {
   "type": "integer"
  },
  "s": {
   "$ref": "#/definitions/S2"
  }
 },
 "type": "object"
}
tpoxa commented 1 year ago

Awesome. That is exactly what I was lacking of with https://github.com/invopop/jsonschema cause it uses only reflect.Type internally and reflect.New().

Thanks!