Пагинация на сервере apollo-graphql

Я хочу реализовать разбиение на страницы на основе курсора на сервере Apollo graphql. Я подготовил схему с требованием разбивки на страницы. Но я застрял на стороне резолвера. Вот моя схема

const typeDefinitions = `
input CreateDeveloperInput {
  # An arbitrary string value with no semantic meaning. Will be included in the
  # payload verbatim. May be used to track mutations by the client.
  clientMutationId: String
  developer: DeveloperInput!
}

type CreateDeveloperPayload {
  clientMutationId: String
  developerEdge(orderBy: DevelopersOrderBy = PRIMARY_KEY_ASC): DevelopersEdge
  query: Query
}
input DeleteDeveloperByIdInput {
  # An arbitrary string value with no semantic meaning. Will be included in the
  # payload verbatim. May be used to track mutations by the client.
  clientMutationId: String
  id: Int!
}

input DeleteDeveloperInput {
  clientMutationId: String
  nodeId: ID!
}

type DeleteDeveloperPayload {
  clientMutationId: String
  developer: Developer
  deletedDeveloperId: ID

  # Our root query field type. Allows us to run any query from our mutation payload.
  query: Query
}

type Developer implements Node {
  nodeId: ID!
  id: Int!
  name: String!
  place: String
  salary: Int
  joiningDate: String
}

input DeveloperCondition {
  id: Int
  name: String
  place: String
  salary: Int
  joiningDate: String
}

input DeveloperInput {
  id: Int
  name: String!
  place: String
  salary: Int
  joiningDate: String
}

input DeveloperPatch {
  id: Int
  name: String
  place: String
  salary: Int
  joiningDate: String
}

type DevelopersConnection {
  # Information to aid in pagination.
  pageInfo: PageInfo!
  totalCount: Int
  edges: [DevelopersEdge]
  nodes: [Developer!]
}

type DevelopersEdge {
  # A cursor for use in pagination.
  cursor: String
  node: Developer!
}

enum DevelopersOrderBy {
  PRIMARY_KEY_ASC
  PRIMARY_KEY_DESC
  NATURAL
  ID_ASC
  ID_DESC
  NAME_ASC
  NAME_DESC
  PLACE_ASC
  PLACE_DESC
  SALARY_ASC
  SALARY_DESC
  JOINING_DATE_ASC
  JOINING_DATE_DESC
}

# The root mutation type which contains root level fields which mutate data.


interface Node {
  # A globally unique identifier. Can be used in various places throughout the system to identify this single value.
  nodeId: ID!
}

# Information about pagination in a connection.
type PageInfo {
  # When paginating forwards, are there more items?
  hasNextPage: Boolean!

  # When paginating backwards, are there more items?
  hasPreviousPage: Boolean!

  # When paginating backwards, the cursor to continue.
  startCursor: String

  # When paginating forwards, the cursor to continue.
  endCursor: String
}

# The root query type which gives access points into the data universe.
type Query implements Node {
   allDevelopers(

    # Read all values in the set before (above) this cursor.
    before: String,

    # Read all values in the set after (below) this cursor.
    after: String, first: Int, last: Int, offset: Int,

    # A condition to be used in determining which values should be returned by the collection.
    condition: DeveloperCondition): DevelopersConnection

  # Exposes the root query type nested one level down. This is helpful for Relay 1
  # which can only query top level fields if they are in a particular form.
  
  nodeId: ID!
}
schema {
query: Query
}

`;

export default [typeDefinitions];

Возможно ли разрешить в резольверах? Если да, может ли кто-нибудь рассказать мне, как это реализовать?


person Seena V P    schedule 06.06.2017    source источник
comment
Реализация будет зависеть от того, какую базу данных вы используете.   -  person Isaac Pak    schedule 20.10.2018


Ответы (1)


Если вы используете Mongo и Mongoose с Apollo Express GraphQL, я нашел три способа разбивки на страницы:

  1. Вы можете создать поле cursor в своей схеме и реализовать свой преобразователь с логикой разбиения на страницы, но я не рекомендую этот метод, если у вас сложная схема, содержащая объединения, интерфейсы и различные вложенные объекты типа, но если вы хотите реализовать это самостоятельно, вот справочник

  2. Вы можете использовать модуль, который вложит вашу модель Mongoose и предоставит вам пагинацию интерфейс, но это требует нескольких изменений в вашей схеме и преобразователях, больше работы, чем третий метод

  3. Вы можете использовать sort, skip и limit из Mongo / Mongoose, но если вы сделаете это самостоятельно, вы можете найти некоторые проблемы, например, если документ был отсортирован по ключу даты, который может иметь разные документы с одной и той же датой, он может дублировать документы и испортить вашу разбивку на страницы, поэтому я рекомендую вам установить плагин разбиения на страницы в вашей схеме Mongoose и используйте его, как любой другой метод из Mongoose

person Community    schedule 16.04.2020