Retrieve the object ID in GraphQL

大憨熊 提交于 2021-02-07 14:47:00

问题


I'd like to know whether it is possible to get the "original id" of an object as the result of the query. Whenever I make a request to the server, it returns the node "global identifier", something like U29saWNpdGFjYW9UeXBlOjEzNTkxOA== .

The query is similar to this one:

{
  allPatients(active: true) {
    edges {
      cursor
      node {
        id
        state
        name
      }
    }
  }

and the return is:

{
  "data": {
      "edges": [
        {
          "cursor": "YXJyYXljb25uZWN0aW9uOjA=",
          "node": {
            "id": "U29saWNpdGFjYW9UeXBlOjEzNTkxOA==",
            "state": "ARI",
            "name": "Brad"
          }
        }
      ]
  }
}

How can I get the "original" id of the object at the database level (e.g. '112') instead of that node unique identifier?

ps.: I am using graphene-python and Relay on the server side.


回答1:


Overriding default to_global_id method in Node object worked out for me:

class CustomNode(graphene.Node):
    class Meta:
        name = 'Node'

    @staticmethod
    def to_global_id(type, id):
        return id


 class ExampleType(DjangoObjectType):
     class Meta:
         model = Example
         interfaces = (CustomNode,)



回答2:


First option, remove relay.Node as interface of your objectNode declaration.

Second option, use custom resolve_id fonction to return id original value.

Example

class objectNode(djangoObjectType):

    .... Meta ....

    id = graphene.Int(source="id")

    def resolve_id("commons args ...."):
        return self.id

Hope it helps




回答3:


To expand on the top answer and for those using SQLAlchemy Object Types, this worked for me:

class CustomNode(graphene.Node):
    class Meta:
        name = 'myNode'

    @staticmethod
    def to_global_id(type, id):
        return id

class ExampleType(SQLAlchemyObjectType):
    class Meta:
        model = Example
        interfaces = (CustomNode, )

If you have other ObjectTypes using relay.Node as the interface, you will need to use a unique name under your CustomNode. Otherwise you will get and assertion error.




回答4:


With this you can retrive the real id in database:

def get_real_id(node_id: str):
    _, product_id_real = relay.Node.from_global_id(global_id=node_id)
    return product_id_real


来源:https://stackoverflow.com/questions/46490229/retrieve-the-object-id-in-graphql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!