简体   繁体   中英

Cursor Based Pagination Naming Convention in GraphQL

In the GraphQL API, I often see naming conventions such as NQ and MQ as parameters used in cursor. This is an example, shown below,

 "data": {
    "items": {
      "totalCount": 351,
      "pageInfo": {
        "hasNextPage": true,
        "hasPreviousPage": false,
        "endCursor": "Mw",
        "startCursor": "MQ"
      },
      "edges": [
        {
          "cursor": "MQ",
          "node": {
            "id": "UGxhY2UtMzUy",
            "displayName": "Redbeard"
          }
        },
        {
          "cursor": "Mg",
          "node": {
            "id": "UGxhY2UtMzUx",
            "displayName": "Frey of Riverrun"
          }
        },
        {
          "cursor": "Mw",
          "node": {
            "id": "QmlsbGVyLTI=",
            "displayName": "Something Else"
          }
        }
      ]
    }
  }
}

Source: https://dev.to/tymate/first-dive-into-graphql-ruby-nak

Other examples include this rails example: https://www.2n.pl/blog/graphql-pagination-in-rails

What are these naming conventions and how would you for example paginate?

The Relay Server Specification defines how pagination should be done in order to be compatible with the Relay GraphQL Client . While it is not the only way how pagination can be done, it has evolved as a standard - at least in examples, since it can be easily referenced.

The section on connections gives more info about how cursors work:

Each edge gets a cursor value. This value is - what they call - an opaque value, meaning it should not be interpreted by the server. It is a reference/a pointer that only the server can interpret . So, if you have a query that gets a bunch of values:

edges: [
  { cursor: "abc", node: {...} },
  { cursor: "def", node: {...} },
  { cursor: "ghi", node: {...} },
  { cursor: "jkl", node: {...} },
  { cursor: "mno", node: {...} }
]

You can request the next page by looking at the cursor of the last element mno and pass it into the query.

query {
  manyQuery(first: 5, after: "mno") {
    edges {
      cursor
      node {...}
    }
  }
}

This will give you the next 5 nodes. See also this section on graphql.org .

So to answer your question: The string can potentially contain anything that the server can use to reference one of your nodes. Eg an id in the database. To remove the temptation to pass in an arbitrary value from the API user this string is often encoded into the base64 format. The value should be meaningless to the client and only be used to be passed around back to the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM