Replies: 1 comment
-
@seyfahni while I'm not sure I'd recommend doing this it is certainly possible. If you protect the OpenAPI doc from concurrent access then your handlers can safely modify it at runtime however you like. For example: https://go.dev/play/p/90XGCi3ewBm mu := sync.Mutex{}
lockMiddleware := func(ctx huma.Context, next func(huma.Context)) {
// Protect concurrent access to the OpenAPI doc. Using a middleware locks
// *before* the validation happens, which also accesses the OpenAPI doc.
mu.Lock()
defer mu.Unlock()
next(ctx)
}
huma.Get(api, "/type/{type}", func(ctx context.Context, input *struct {
Type string `path:"type" enum:"initial"`
}) (*struct{}, error) {
// TODO: Do something with type...
fmt.Println("You sent me", input.Type)
return nil, nil
}, WithMiddleware(lockMiddleware))
huma.Put(api, "/type/{type}", func(ctx context.Context, input *struct {
Type string `path:"type"`
}) (*struct{}, error) {
s := api.OpenAPI().Paths["/type/{type}"].Get.Parameters[0].Schema
s.Enum = append(s.Enum, input.Type)
s.PrecomputeMessages()
// TODO: update output schemas via `OneOf`...
return nil, nil
}, WithMiddleware(lockMiddleware)) Modifying the param's Assuming you have a lot more reads than writes you could also make this more efficient using a Hopefully that helps! |
Beta Was this translation helpful? Give feedback.
-
I've got a requirement for an endpoint that has a dynamic schema:
In general
/type/{type}
returns just is a JSON object that maps a key to some kind of value, but for specific paths it might be more concrete.For
/type/A
if could have a schema that a keyfoo
exists with a string value and keybar
with an integer value while/type/B
should have a keybaz
with an array of stings. These types are however dynamic, so I must be able to add more of them (or remove them) during runtime (there will be a different API endpoint for it).Is it theoretically possible to use huma with this kind of requirement? Ideally I'd still want the schema to be linked like in normal endpoints where it is generated from the type (
Link: </schemas/TypeABody.json>; rel="describedBy"
).I am fairly new to this library, so please forgive me if I missed anything obvious.
I've seen in
hint
in theRegistry.Schema(..., hint string) *Schema
method and theSchemaProvider
interface, but how can I leverage either of those (if even possible) to do what I want? Which is the better way?Update: I tried to provide a dynamic schema, but the methods providing custom schemata were never called.
Additionally, this causes me to loose the
Link
response header. I suspect that this is due to my usage ofmap[string]any
.Experimental Code for SchemaProvider
Experimental Code for Registry
Beta Was this translation helpful? Give feedback.
All reactions