MCPcopy
hub / github.com/danielgtaylor/huma / OnAddOperation

Method OnAddOperation

transforms.go:85–153  ·  view source on GitHub ↗

OnAddOperation is triggered whenever a new operation is added to the API, enabling this transformer to precompute & cache information about the response and schema.

(oapi *OpenAPI, op *Operation)

Source from the content-addressed store, hash-verified

83// enabling this transformer to precompute & cache information about the
84// response and schema.
85func (t *SchemaLinkTransformer) OnAddOperation(oapi *OpenAPI, op *Operation) {
86 t.oapi = oapi
87
88 // Update registry to be able to get the type from a schema ref.
89 // Register the type in t.types with the generated ref
90 if op.RequestBody != nil && op.RequestBody.Content != nil {
91 for _, content := range op.RequestBody.Content {
92 t.addSchemaField(oapi, content)
93 }
94 }
95
96 // Figure out if there should be a base path prefix. This might be set when
97 // using a sub-router / group or if the gateway consumes a part of the path.
98 schemasPath := t.schemasPath
99 if prefix := getAPIPrefix(oapi); prefix != "" {
100 schemasPath = path.Join(prefix, schemasPath)
101 }
102
103 registry := oapi.Components.Schemas
104 for _, resp := range op.Responses {
105 for _, content := range resp.Content {
106 if t.addSchemaField(oapi, content) {
107 continue
108 }
109
110 // Then, create the wrapper Go type that has the $schema field.
111 typ := deref(registry.TypeFromRef(content.Schema.Ref))
112
113 extra := schemaField{
114 Schema: schemasPath + "/" + path.Base(content.Schema.Ref) + ".json",
115 }
116
117 fieldIndexes := []int{}
118 fields := []reflect.StructField{
119 reflect.TypeFor[schemaField]().Field(0),
120 }
121 for i := 0; i < typ.NumField(); i++ {
122 f := typ.Field(i)
123 if f.IsExported() {
124 fields = append(fields, f)
125
126 // Track which fields are exported, so we can copy them over.
127 // It's preferred to track/compute this here to avoid allocations in
128 // the transform function from looking up what is exported.
129 fieldIndexes = append(fieldIndexes, i)
130 }
131 }
132
133 func() {
134 defer func() {
135 if r := recover(); r != nil {
136 // Catch some scenarios that just aren't supported in Go at the
137 // moment. Logs an error so people know what's going on.
138 // https://github.com/danielgtaylor/huma/issues/371
139 fmt.Fprintln(os.Stderr, "Warning: unable to create schema link for type", typ, ":", r)
140 }
141 }()
142 newType := reflect.StructOf(fields)

Callers

nothing calls this directly

Calls 4

addSchemaFieldMethod · 0.95
getAPIPrefixFunction · 0.85
derefFunction · 0.70
TypeFromRefMethod · 0.65

Tested by

no test coverage detected