【问题标题】:GraphQL Sorting custom typeGraphQL 排序自定义类型
【发布时间】:2016-10-21 05:50:31
【问题描述】:

我有一个投票应用程序的graphql环境,有用户、投票和投票。 我在架构中的主查询中,对我的应用程序中所有民意调查的查询(带有限制等选项......),我也有每个用户的民意调查字段,我通常希望所有民意调查都是可排序的使用我自己的业务逻辑(例如,大多数投票、最近投票等),我不希望为每个投票字段定义排序逻辑,并且通常使类型可排序。 如何做到这一点?

这是我的代码,我目前只使用模拟数据库来测试和确定我需要什么架构。现在到 GQL。

userType = new GraphQLObjectType({
  name: 'User',
  description: 'Registered user',
  fields: (() => ({
    id: {
      type: new GraphQLNonNull(GraphQLID)
    },
    email: {
      type: GraphQLString
    },
    password: {
      type: GraphQLString
    },
    username: {
      type: GraphQLString
    },
    polls: { // this should be sortable
      type: new GraphQLList(pollType),
      resolve: user => db.getUserPolls(user.id)
    },
    votes: {
      type: new GraphQLList(voteType),
      resolve: user => db.getUserVotes(user.id)
    }
  })),
  resolve: id => db.getUsers()[id]
});

pollType = new GraphQLObjectType({
  name: 'Poll',
  description: 'Poll which can be voted by registered users',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLID)
    },
    title: {
      type: GraphQLString
    },
    options: {
      type: new GraphQLList(GraphQLString),
    },
    votes: {
      type: new GraphQLList(voteType),
      resolve: poll => db.getPollVotes(poll.id)
    },
    author: {
      type: userType,
      resolve: poll => db.getPollAuthor(poll.id)
    },
    timestamp: {
      type: GraphQLDate
    }
  })
});

voteType = new GraphQLObjectType({
  name: 'Vote',
  description: 'User vote on a poll',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLID)
    },
    user: {
      type: userType,
      resolve: vote => db.getVoteUser(vote.id)
    },
    poll: {
      type: pollType,
      resolve: vote => db.getVotePoll(vote.id)
    },
    vote: {
      type: GraphQLInt
    },
    timestamp: {
      type: GraphQLDate
    }
  })
});

let schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: () => ({
      user: {
        type: userType,
        args: {
          id: {
            type: new GraphQLNonNull(GraphQLID)
          }
        },
        resolve: (root, {id}) => db.getUsers()[id]
      },
      polls: { //this should also be sorted
        type: new GraphQLList(pollType),
        resolve: () => db.getPolls()
      },
      votes: {
        type: new GraphQLList(voteType),
        resolve: () => db.getVotes()
      }
    })
  })
});

【问题讨论】:

    标签: javascript graphql relayjs graphql-js


    【解决方案1】:

    您可以尝试使用您想要作为输入字段的自定义排序字段创建一个 Sortable 类型,并将您的 Poll 类型设置为实现 Sortable 接口的列表。

    【讨论】:

      【解决方案2】:

      我不确定您要做什么,但也许这对您有帮助:https://github.com/javascriptiscoolpl/graphQL-tinySQL(检查命令文件夹和 sortBy.js 文件)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-04
        • 1970-01-01
        • 2021-11-20
        • 2017-09-18
        • 2019-08-28
        • 2011-03-20
        • 2019-10-12
        • 1970-01-01
        相关资源
        最近更新 更多