Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes to UUID schema generation #64

Closed
danicc097 opened this issue Apr 24, 2023 · 6 comments
Closed

Changes to UUID schema generation #64

danicc097 opened this issue Apr 24, 2023 · 6 comments

Comments

@danicc097
Copy link

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
Copy link

B87 commented Feb 7, 2024

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
Copy link
Author

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:

  • github.com/swaggest/jsonschema-go v0.3.64
  • github.com/swaggest/openapi-go v0.2.44

@B87
Copy link

B87 commented Feb 7, 2024

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:

  • github.com/swaggest/openapi-go v0.2.45
  • github.com/swaggest/jsonschema-go v0.3.64

@vearutop
Copy link
Member

vearutop commented Feb 7, 2024

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
Copy link

B87 commented Feb 7, 2024

@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
Copy link
Member

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())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants