Reputation: 5106
I have a graphql environment of a voting application, there are users, polls and votes. I have in my main query in the schema, the query for all the polls in my application (with option to limit and so on...), I also have a polls field for each user, I want generally all polls to be sortable using my own business logic (e.g. most votes, recent, etc...), I'd prefer not to define the sorting logic for each field of polls, and make the type sortable in general. How can this be done?
This is my code, I'm currently only using mock database for testing and figuring out what schema I need. Very now to 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()
}
})
})
});
Upvotes: 1
Views: 2438
Reputation: 3
I am not sure what you are trying to do but maybe this help you: https://github.com/javascriptiscoolpl/graphQL-tinySQL (check the command folder and sortBy.js file there)
Upvotes: 0
Reputation: 1922
You can try creating a Sortable type with the custom sorting fields that you want as the input fields, and have your Poll type be a list that implements the Sortable interface.
Upvotes: 0