oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Support generating struct field accessor methods

Open 0xch4z opened this issue 9 months ago • 2 comments

Support generating GetXXXXX accessor methods for structs. Either by default or by output option. This would make it easy to build interfaces around common fields for generated structs.

Go's protobuf generator does this for all message generated structs here. (example)

With the following schema:

components:
  schemas:
    Server:
      type: object
      properties:
        metro:
          type: string
        # ...
    Drive:
      type: object
      properties:
        metro:
          type: string
        # ...
      required:
        - name

These would be generated as:

type Server struct {
        Metro string `json:"metro"`
        // ...
}

func (s *Server) GetMetro() string {
       return s.Metro
}

type Drive struct {
        Metro string `json:"metro"`
        // ...
}

func (d *Drive) GetMetro() string {
       return d.Metro
}

So the user could do something like:

// Abstract type fulfilled by generated structs with `metro: {type: string}`
type LocalizedResource interface {
        GetMetro() string
}

var (
        // The generated structs implement LocalizedResource.
        _ LocalizedResource = (nil)(*Server)
        _ LocalizedResource = (nil)(*Drive)
)

0xch4z avatar Apr 12 '25 18:04 0xch4z

It's partly supported by the nullable type option, but surely will be much better here

0rid avatar Apr 20 '25 12:04 0rid

This is something that should be opt-in, in case folks don't want the additional methods / introducing large scale generated code changes.

Something else to look into will be how this works for fields with ie anyOf that already have generated methods

jamietanna avatar Apr 21 '25 10:04 jamietanna