swaggest / openapi-go

OpenAPI structures for Go
https://pkg.go.dev/github.com/swaggest/openapi-go/openapi3
MIT License
223 stars 18 forks source link

Changes to UUID schema generation #64

Closed danicc097 closed 3 days ago

danicc097 commented 1 year ago

Describe the bug After upgrading from openapi-go v0.2.25 to openapi-go v0.2.30, I noticed that now google/uuid is generated as a byte array:

UuidUUID: # v0.2.25
      type: string
UuidUUID: 
      items:
        minimum: 0
        type: integer
      nullable: true
      type: array

I can easily work around it with another intercept on openapi3.Reflector.DefaultOptions:

jsonschema.InterceptType(func(v reflect.Value, s *jsonschema.Schema) (stop bool, err error) {
        if s.ReflectType == reflect.TypeOf(uuid.New()) {
            s.Type = &jsonschema.Type{SimpleTypes: pointers.New(jsonschema.SimpleType("string"))}
            s.Items = &jsonschema.Items{}
        }
        return false, nil
    })

but I was wondering if this is an intended change (indeed it's type UUID [16]byte, but somehow it was generated as string in 0.2.25). Maybe a short mention plus this example in the docs is useful, since everyone will want to use the string version of their own uuid library by default I would think.

Additional context Current go.mod

      github.com/swaggest/openapi-go v0.2.30
        github.com/swaggest/jsonschema-go v0.3.50 // indirect
        github.com/swaggest/refl v1.1.0 // indirect
B87 commented 4 months ago

Hi! I'm facing the same issue, represent a google UUID as a string on my schema.

What is the best way of doing it? I see that jsonschema.InterceptType has been deprecated

danicc097 commented 4 months ago

I append jsonschema.InterceptSchema to openapi3.Reflector's DefaultOptions with

// jsonschema.InterceptSchema(func(params jsonschema.InterceptSchemaParams) (stop bool, err error)
t := params.Schema.ReflectType
if t.Kind() == reflect.Ptr {
  t = t.Elem()
}
if t == reflect.TypeOf(uuid.New()) {
  params.Schema.Type = &jsonschema.Type{SimpleTypes: pointers.New(jsonschema.String)}
  params.Schema.Pattern = pointers.New("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
  params.Schema.Items = &jsonschema.Items{}
  // oapi-codegen
  params.Schema.ExtraProperties = map[string]any{
      "x-go-type": "uuid.UUID",
      "x-go-type-import": map[string]any{
          "name": "uuid",
          "path": "github.com/google/uuid",
      },
      "x-is-generated": true,
  }
}

using:

B87 commented 4 months ago

Thank you so much @danicc097, your approach worked like a charm. I noticed that when doing this you will need to add an example manually since the struct example for path parameters won't be used on the spec generation.

This is how my code looks like now:

reflector.DefaultOptions = append(reflector.DefaultOptions, jsonschema.InterceptSchema(
        func(params jsonschema.InterceptSchemaParams) (stop bool, err error) {
            t := params.Schema.ReflectType
            if t.Kind() == reflect.Ptr {
                t = t.Elem()
            }
            if t == reflect.TypeOf(uuid.New()) {
                params.Schema.Type = &jsonschema.Type{SimpleTypes: &strSchema}
                params.Schema.Pattern = &uuidPattern
                params.Schema.Items = &jsonschema.Items{}
                // oapi-codegen
                params.Schema.Examples = []interface{}{"cdb15f83-1c5d-4727-98d1-8924ccd1fc01"}
                params.Schema.ExtraProperties = map[string]any{
                    "x-go-type": "uuid.UUID",
                    "x-go-type-import": map[string]any{
                        "name": "uuid",
                        "path": "github.com/google/uuid",
                    },
                    "x-is-generated": true,
                }
            }
            return false, nil
        }))

using:

vearutop commented 4 months ago

I'm sorry this issue already took me so long, I'll try to come up with a proper solution soon. In meanwhile, one of the workarounds is to declare desired schema with type mapping:

https://github.com/swaggest/rest/blob/v0.2.61/_examples/advanced-generic-openapi31/router.go#L84-L89

    // Create custom schema mapping for 3rd party type.
    uuidDef := jsonschema.Schema{}
    uuidDef.AddType(jsonschema.String)
    uuidDef.WithFormat("uuid")
    uuidDef.WithExamples("248df4b7-aa70-47b8-a036-33ac447e668d")
    jsr.AddTypeMapping(uuid.UUID{}, uuidDef)
B87 commented 4 months ago

@vearutop Thanks for the example, your approach looks cleaner. It would be nice to have a native uuid integration but this is good enough for me.

vearutop commented 3 days ago

Hello, with latest version (v0.2.53) google and gofrs UUID types are recognized automatically.

Please feel free to reopen if there is anything else to do here.

func TestNewReflector_uuid(t *testing.T) {
    r := openapi3.NewReflector()

    oc, err := r.NewOperationContext(http.MethodPost, "/")
    require.NoError(t, err)

    type req struct {
        P1 uuid.UUID `query:"p1"`
        P2 uuid.UUID `json:"p2"`
    }

    type resp struct {
        P3 uuid.UUID `json:"p3"`
    }

    oc.AddReqStructure(req{})
    oc.AddRespStructure(resp{})

    require.NoError(t, r.AddOperation(oc))

    assertjson.EqMarshal(t, `{
      "openapi":"3.0.3","info":{"title":"","version":""},
      "paths":{
        "/":{
          "post":{
            "parameters":[
              {
                "name":"p1","in":"query",
                "schema":{"$ref":"#/components/schemas/UuidUUID"}
              }
            ],
            "requestBody":{
              "content":{
                "application/json":{"schema":{"$ref":"#/components/schemas/Openapi3TestReq"}}
              }
            },
            "responses":{
              "200":{
                "description":"OK",
                "content":{
                  "application/json":{"schema":{"$ref":"#/components/schemas/Openapi3TestResp"}}
                }
              }
            }
          }
        }
      },
      "components":{
        "schemas":{
          "Openapi3TestReq":{
            "type":"object",
            "properties":{"p2":{"$ref":"#/components/schemas/UuidUUID"}}
          },
          "Openapi3TestResp":{
            "type":"object",
            "properties":{"p3":{"$ref":"#/components/schemas/UuidUUID"}}
          },
          "UuidUUID":{
            "type":"string","format":"uuid",
            "example":"248df4b7-aa70-47b8-a036-33ac447e668d"
          }
        }
      }
    }`, r.SpecSchema())
}