簡體   English   中英

如何修改 graphql-ruby 中子字段的上下文?

[英]How to modify context for child fields in graphql-ruby?

我有這樣的查詢:

query {
  organizations {
    id
    name
    itemA {
      fieldA
      fieldB
    }
  }
}

回報

"data": {
  "organizations": [
    {
      "id": 123, 
      "name": "first org",
      "itemA": {
        "fieldA": "some value A",
        "fieldB": "other value B",
      }
    },
    {
      "id": 321, 
      "name": "other org",
      "itemA": {
        "fieldA": "other value A",
        "fieldB": "value B",
      }
    }
  ]
}

一個用戶可以訪問多個組織,但對每個組織具有不同的訪問權限。

fieldAfieldB被解析以驗證訪問時,我需要有 organization.id。

我嘗試在解析器中使用context.merge_scoped:(organiozation_id. org.id)作為字段,返回單個組織。 看起來它滿足了我的需要,子字段在context收到了正確的值,但我不確定。 通常沒有關於該方法和scoped_context的文檔。

另外,如果scoped_context是我所需要的,我如何為項目列表設置它?


UPD:示例查詢

query {
  organizations { // I need to pass item of this list to resolver of ItemA
    someModel{
      otherModel {
        itemA // access depened on organization`
      }
    }
  }
}

我不是 100% 確定我遇到了你的問題,但我認為你需要的對 GQL 應該是“透明的”。

您需要兩件事才能正確列出組織的“項目”:1. 哪個組織和 2. 誰在提問:

# type organization
def itemA
  object # this is 1, the organization, current node in the graph
    .get_fields_accessible_by(context[:who_is_asking]) # this is requirement 2
end

如您所見,似乎根本沒有理由操縱上下文。 (除非我完全錯過了這一點,所以請隨時修改您的問題以澄清)。

你能試試:

context[:organisation] = object #set this value in your organisation model

使用current[:organisation]在另一個 model 中訪問它

此外,您可以創建輔助方法

就像是

def current_organisation
  context[:current_organisation]
end

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM