almanegra
almanegra

Reputation: 663

Retrieve the object ID in GraphQL

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.

Upvotes: 7

Views: 3411

Answers (4)

Floder
Floder

Reputation: 21

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

Upvotes: 2

bashful_ben
bashful_ben

Reputation: 21

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.

Upvotes: 2

alexxmagpie
alexxmagpie

Reputation: 367

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,)

Upvotes: 6

Charles DOUKOURE
Charles DOUKOURE

Reputation: 161

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

Upvotes: 3

Related Questions