1 回答

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
FieldContext我認(rèn)為您可以在父解析器中找到參數(shù)。graphql.GetFieldContext你可以這樣得到它:
// Version is the resolver for the version field.
func (r *mainResolver) Version(ctx context.Context, obj *models.Main) (*models.Version, error) {
device := graphql.GetFieldContext(ctx).Parent.Args["device"].(string)
// ...
}
該字段Args是一個map[string]interface{},因此您可以按名稱訪問參數(shù),然后將它們鍵入斷言為它們應(yīng)該是什么。
如果解析器嵌套了多個級別,您可以編寫一個函數(shù)沿著上下文鏈向上遍歷,直到找到具有該值的祖先。使用 Go 1.18+ 泛型,該函數(shù)可以重用于任何值類型,使用類似于 json.Unmarshal 的模式:
func FindGqlArgument[T any](ctx context.Context, key string, dst *T) {
if dst == nil {
panic("nil destination value")
}
for fc := graphql.GetFieldContext(ctx); fc != nil; fc = fc.Parent {
v, ok := fc.Args[key]
if ok {
*dst = v.(T)
}
}
// optionally handle failure state here
}
并將其用作:
func (r *deeplyNestedResolver) Version(ctx context.Context, obj *models.Main) (*models.Version, error) {
var device string
FindGqlArgument(ctx, "device", &device)
}
如果這不起作用,也可以嘗試 with graphql.GetOperationContext,這基本上沒有記錄......(歸功于@Shashank Sachan)
graphql.GetOperationContext(ctx).Variables["device"].(string)
- 1 回答
- 0 關(guān)注
- 122 瀏覽
添加回答
舉報