relay-mongoose-connection
v1.0.1
Published
Mongoose connection for Relay
Downloads
20
Readme
relay-mongodb-connection
Like
connectionFromMongoCursor()
but for Mongoose queries
Install
npm install --save shenyzore/relay-mongoose-connection
Usage
Give it a query from mongoose, and it handles pagination int he same way graphql-relay does for arrays.
At a glance
Pass it a Mongoose query and connectionArgs
, and it's happy.
async resolve(obj, { ...args }) {
return await connectionFromMongooseQuery(
User.find({}),
args
);
}
Optionally give it a mapper function:
async resolve(obj, { ...args }) {
return await connectionFromMongoCursor(
User.find({}),
args,
(user) => Object.assign(user, { id: user._id })
);
}
Example
// ...
import connectionFromMongooseQuery from 'relay-mongoose-connection';
// ...
// Instead of resolving, synchronously returns a Mongoose Query.
function getSpaceshipsForUser(userId) {
return Spaceships.find({
user: new ObjectId(userId)
});
}
export const GraphQLUser = new GraphQLObjectType({
name: 'User',
fields: {
id: globalIdField('User'),
spaceships: {
type: SpaceshipConnection,
args: {
...connectionArgs,
},
async resolve(user, { ...args }) {
const spaceshipCursor = getSpaceshipsForUser(user._id);
return await connectionFromMongooseQuery(spaceshipCursor, args);
}
}
}
});
connectionFromMongooseQuery
automatically skips and limits the Mongoose Query so that only the necessary documents are retrieved from the database.
Changelog
See CHANGELOG.md
Testing
Set a MongoDB connection string as environment variable:
export MONGO_CONNECTION_STRING=mongodb://192.168.99.100/mongodbconnection
Then run tests
npm test
License
MIT © Mikael Berg