Skip to content

heysailor/relay-mongodb-connection

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

89 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

relay-mongodb-connection Build Status Coverage Status

Like connectionFromArray() but for MongoDB cursors

Install

npm install --save relay-mongodb-connection

Usage

Give it a cursor from mongodb, and it handles pagination int he same way graphql-relay does for arrays.

import connectionFromMongoCursor from 'relay-mongodb-connection';

Also supports mongoose's querys and aggregations.

import { connectionFromMongooseQuery } from 'relay-mongodb-connection';
import { connectionFromMongooseAggregate } from 'relay-mongodb-connection';

At a glance

Pass it a MongoDB cursor and connectionArgs, and it's happy.

resolve(obj, { ...args }) {
  return connectionFromMongoCursor(
    db.collection('users').find({}),
    args
  );
}

Optionally give it a mapper function:

resolve(obj, { ...args }) {
  return connectionFromMongoCursor(
    db.collection('users').find({}),
    args,
    (user) => Object.assign(user, { id: user._id })
  );
}

And for Mongoose users:

resolve(obj, { ...args }) {
  return connectionFromMongooseQuery(
    User.find({}),  // User.aggregate() also works
    args,
    (user) => Object.assign(user, { id: user._id })
  );
}

Example

// ...
import connectionFromMongoCursor from 'relay-mongodb-connection';
// ...

// Instead of resolving, synchronously returns a MongoDB Cursor.
function getSpaceshipsForUser(userId) {
  return db.collection('spaceships').find({
    user: new ObjectId(userId)
  });
}

export const GraphQLUser = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: globalIdField('User'),
    spaceships: {
      type: SpaceshipConnection,
      args: {
        ...connectionArgs,
      },
      resolve(user, { ...args }) {
        const spaceshipCursor = getSpaceshipsForUser(user._id);
        return connectionFromMongoCursor(spaceshipCursor, args);
      }
    }
  }
});

connectionFromMongoCursor automatically skips and limits the MongoDB Cursor so that only the necessary documents are retrieved from the database.

Changelog

See CHANGELOG.md

Testing

MONGO_URL=mongodb://192.168.99.100/mongodbconnection npm test

License

MIT © Mikael Berg

About

Create Relay connections from MongoDB cursors

Resources

Stars

Watchers

Forks

Packages

No packages published