Implementing pagination in vanilla GraphQL - mongodb

Every tutorial I have found thus far has achieved pagination in GraphQL via Apollo, Relay, or some other magic framework. I was hoping to find answers in similar asked questions here but they don't exist. I understand how to setup the queries but I'm unclear as to how I would implement the resolvers.
Could someone point me in the right direction? I am using mongoose/MongoDB and ES5, if that helps.
EDIT: It's worth noting that the official site for learning GraphQL doesn't have an entry on pagination if you choose to use graphql.js.
EDIT 2: I love that there are some people who vote to close questions before doing their research whereas others use their knowledge to help others. You can't stop progress, no matter how hard you try. (:

Pagination in vanilla GraphQL
// Pagination argument type to represent offset and limit arguments
const PaginationArgType = new GraphQLInputObjectType({
name: 'PaginationArg',
fields: {
offset: {
type: GraphQLInt,
description: "Skip n rows."
},
first: {
type: GraphQLInt,
description: "First n rows after the offset."
},
}
})
// Function to generate paginated list type for a GraphQLObjectType (for representing paginated response)
// Accepts a GraphQLObjectType as an argument and gives a paginated list type to represent paginated response.
const PaginatedListType = (ItemType) => new GraphQLObjectType({
name: 'Paginated' + ItemType, // So that a new type name is generated for each item type, when we want paginated types for different types (eg. for Person, Book, etc.). Otherwise, GraphQL would complain saying that duplicate type is created when there are multiple paginated types.
fields: {
count: { type: GraphQLInt },
items: { type: new GraphQLList(ItemType) }
}
})
// Type for representing a single item. eg. Person
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: {
id: { type: new GraphQLNonNull(GraphQLID) },
name: { type: GraphQLString },
}
})
// Query type which accepts pagination arguments with resolve function
const PersonQueryTypes = {
people: {
type: PaginatedListType(PersonType),
args: {
pagination: {
type: PaginationArgType,
defaultValue: { offset: 0, first: 10 }
},
},
resolve: (_, args) => {
const { offset, first } = args.pagination
// Call MongoDB/Mongoose functions to fetch data and count from database here.
return {
items: People.find().skip(offset).limit(first).exec()
count: People.count()
}
},
}
}
// Root query type
const QueryType = new GraphQLObjectType({
name: 'QueryType',
fields: {
...PersonQueryTypes,
},
});
// GraphQL Schema
const Schema = new GraphQLSchema({
query: QueryType
});
and when querying:
{
people(pagination: {offset: 0, first: 10}) {
items {
id
name
}
count
}
}
Have created a launchpad here.

There's a number of ways you could implement pagination, but here's two simple example resolvers that use Mongoose to get you started:
Simple pagination using limit and skip:
(obj, { pageSize = 10, page = 0 }) => {
return Foo.find()
.skip(page*pageSize)
.limit(pageSize)
.exec()
}
Using _id as a cursor:
(obj, { pageSize = 10, cursor }) => {
const params = cursor ? {'_id': {'$gt': cursor}} : undefined
return Foo.find(params).limit(pageSize).exec()
}

Related

Mongoose Schema planning: using ObjectID reference or using array of type: [otherSchema]?

I'm currently planning out the database structure for an app I'm building, and something in this linked answer raised some questions for me.
In the structure that Shivam proposed, he sometimes references another collection directly, in other words within one Schema he defines the type of a field to be an array of another schema type. Example:
import { Schema } from "mongoose";
import { QuestionSchema } from "./question-schema";
const mongoose = require('mongoose');
export const QuestionSetSchema: Schema = new Schema({
questionSet: {
type: [QuestionSchema],
validate: {
validator: function(value: any) {
return value.length === 12;
},
message: 'Question set must be 12.'
}
},
}, {
timestamps: true
});
In other cases, he only uses an ObjectID reference to another schema/collection:
export const CandidateSchema: Schema = new Schema({
name: String,
email: String, // you can store other candidate related information here.
totalAttempt: {
type: Number,
default: 0,
validate: {
validator: function(value: number) {
return value === 3;
},
message: 'You have already done three attempts.'
}
},
candidateQuestionAnswers: {
type: [Schema.Types.ObjectId],
ref: 'CandidateQuesAnswer'
}
}, {
timestamps: true
});
What are the use cases for each of the above? Does the "type:[otherSchema]" method actually embed instances of that collection or does it only provide their properties to the Schema they are called from?

How do I use GraphQL with Mongoose and MongoDB without creating Mongoose models

Creating models in Mongoose is quite pointless since such models are already created with GraphQL and existing constructs (ie TypeScript interface).
How can we get GraphQL to use Mongoose's operations on models supplied from GraphQL without having to recreate models in Mongoose?
Also, it almost seems as if there should be a wrapper for GraphQL that just communicates with the database, avoiding having to write MyModel.findById etc
How does one do that?
Every example on the Internet that talks about GraphQL and Mongodb uses Mongoose.
You should look at GraphQL-to-MongoDB, or how I learned to stop worrying and love generated query APIs. It talks about a middleware package that leverages GraphQL's types to generate your GraphQL API and parses requests sent from clients into MongoDB queries. It more or less skips over Mongoose.
Disclaimer: this is my blog post.
The package generates GraphQL input types for your schema field args, and wraps around the resolve function to parse them into MongoDB queries.
Given a simple GraphQLType:
const PersonType = new GraphQLObjectType({
name: 'PersonType',
fields: () => ({
age: { type: GraphQLInt },
name: {
type: new GraphQLNonNull(new GraphQLObjectType({
name: 'NameType',
fields: () => ({
firstName: { type: GraphQLString },
lastName: { type: GraphQLString }
})
}))
}
})
});
For the most common use case, you'll build a field in the GraphQL schema with a getMongoDbQueryResolver and getGraphQLQueryArgs. The filter, projection, and options provided by the wrapper can be passed directly to the find function.
person: {
type: new GraphQLList(PersonType),
args: getGraphQLQueryArgs(PersonType),
resolve: getMongoDbQueryResolver(PersonType,
async (filter, projection, options, source, args, context) =>
await context.db.collection('person').find(filter, projection, options).toArray()
)
}
An example of a query you could send to such a field:
{
person (
filter: {
age: { GT: 18 },
name: {
firstName: { EQ: "John" }
}
},
sort: { age: DESC },
pagination: { limit: 50 }
) {
name {
lastName
}
age
}
}
There's also a wrapper and argument types generator for mutation fields.

GraphQL & MongoDB cursors

I'm confused about what should be the relation between GraphQL's cursors and MongoDB's cursors.
I'm currently working on a mutation that creates an object (mongo document) and add it to an existing connection (mongo collection). When adding the object, the mutation returns the added edge. Which should look like:
{
node,
cursor
}
While node is the actual added document, I'm confused on what should be returned as the cursor.
This is my Mutation:
const CreatePollMutation = mutationWithClientMutationId({
name: 'CreatePoll',
inputFields: {
title: {
type: new GraphQLNonNull(GraphQLString),
},
multi: {
type: GraphQLBoolean,
},
options: {
type: new GraphQLNonNull(new GraphQLList(GraphQLString)),
},
author: {
type: new GraphQLNonNull(GraphQLID),
},
},
outputFields: {
pollEdge: {
type: pollEdgeType,
resolve: (poll => (
{
// cursorForObjectInConnection was used when I've tested using mock JSON data,
// this doesn't work now since db.getPolls() is async
cursor: cursorForObjectInConnection(db.getPolls(), poll),
node: poll,
}
)),
},
},
mutateAndGetPayload: ({ title, multi, options, author }) => {
const { id: authorId } = fromGlobalId(author);
return db.createPoll(title, options, authorId, multi); //promise
},
});
Thanks!
Probably a bit late for you, but maybe it will help someone else stumbling across this problem.
Just return a promise from your resolve method. Then you can create your cursor using your actual polls array. Like so:
resolve: (poll =>
return db.getPolls().then(polls => {
return { cursor: cursorForObjectInConnection(polls, poll), node: poll }
})
)
But careful, your poll and the objects in polls have different origins now and are not strictly equal. As cursorForObjectInConnection uses javascript's indexOf your cursor would probably end up being null. To prevent this you should find the object index yourself and use offsetToCursor to construct your cursor as discussed here.

Bind allowedValues to values from a collection in simple-schema

I'm using aldeed:simple-schema and here's the code:
Cities = new Mongo.Collection('cities');
Cities.insert({
name: 'Oslo'
});
Cities.insert({
name: 'Helsinki'
});
Contact = new SimpleSchema({
city: {
type: String,
allowedValues: Cities.find().map((e) => e.name) // written ES6-style for readability; in fact, here goes an ES5 anonymous function definition
}
});
What it does is explicitly binds currently existing cities from Cities collection to Contact schema's certain field's allowed values, so it's then impossible to store any other value than "Oslo" or "Helsinki".
But when posting a quickForm, the field (select, actually) has no options.
If I rewrite the mapping function to
(e) => {
console.log(e);
return e.name;
}
then I get
I20150911-18:07:23.334(4)? { _id: 'GLAbPa6N4W4c9GZZh', name: 'Oslo' }
I20150911-18:07:23.333(4)? { _id: 'vb64X5mKpMbDNzCkw', name: 'Helsinki' }
in server logs, which makes me think the mapping function is correct.
At the very same time, doing all this in Mongo console returns desirable result:
production-d:PRIMARY> db.cities.find().map(function (e) { return e.name; });
[ "Oslo", "Helsinki" ]
What do I do wrong? Is it impossible to fill the simple-schema's allowedValues array at the run time?

How to have an optional association using Waterline?

I'm using sails.js for a project and everything is going fine so far. Except that I don't know how to have an optional association between my two models. If I don't specify one, then if I use populate() it takes the first one available.
I have those two models:
// Book.js
module.exports = {
attributes: {
title: 'string',
serie: { model: 'serie' }
},
};
// Serie.js
module.exports = {
attributes: {
name: 'string',
books: { collection: 'book', via: 'serie' }
}
};
If I do this:
$ sails console
> Book.create({title: "Title"}).exec(function(err, book) {
Book.findOne({id: book.id }).populateAll().exec(function(err, book) {
console.log(book);
});
});
I get this:
{
serie: { name: 'Previously inserted serie' },
title: 'Title',
id: '55d6230122e3b1e70d877351'
}
Why isn't serie empty ? When inserting the book, I didn't specify any serie but it is still linked to a random one.
It was actually a bug from the sails-mongo adapter. I made a pull request that fixes it.