graphql-mongodb-projection

Uses GraphQL resolve info to generate mongoDB projections

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
graphql-mongodb-projection
30131.1.16 years ago8 years agoMinified + gzip package size for graphql-mongodb-projection in KB

Readme

graphql-mongodb-projection
Build Status David npm version PRs Welcome
Uses GraphQL resolve's info to generate mongoDB projections
Supports:
  • Fields
  • InlineFragments
  • FragmentSpreads
  • Relay Edge Node Pattern

references:

Usage

$ npm install --save-dev graphql-mongodb-projection

Just add it has a second parameter in a .findOne inside the resolve function, make sure to pass it info. (example using koa with express is the 3rd parameter).
import graphqlMongodbProjection from 'graphql-mongodb-projection'

const user = {
  type: UserType,
  description: 'Get User by ID',
  args: {
    _id: {type: new GraphQLNonNull(GraphQLString)},
  },
  resolve(root, args, ctx, info) {
    return db.collection('users').findOne({_id: ObjectId(args._id)}, graphqlMongodbProjection(info))
  }
}

Conditional fields

resolve(root, args, ctx, info) {
  const projection = graphqlMongodbProjection(info, {
    // if asked for `avatar` will project `profile.avatar`
    'avatar': 'profile.avatar',
    // always return `verified`
    'verified': true
  })
}

on GraphiQL
fragment userInfo on User {
  email
  firstname
}

query {

  # standard fields
  test1: user(_id: "574f263d19bb93d88f1d586d") {
  	_id
  	email
  	firstname
  	lastname
  }

  # with fragment
  test2: user(_id: "573124fb17c1b1631b00ccd1") {
    ...userInfo
  }

  # with fragment
  test3: user(_id: "573124fb17c1b1631b00ccd1") {
    ...userInfo
  }

  # edge node pattern
  test4: users {
    edges {
      node {
  			email
  			firstname
      }
    }
  }

  # edge node pattern with fragment
  test5: users {
    edges {
      node {
				...userInfo
      }
    }
  }
}

MongoDB Projection
{
  "first_name": true,
  "email": true
}

Result
{
  "data": {
    "test1": {
      "_id": "574f263d19bb93d88f1d586d",
      "email": "roberto@gmail.com",
      "firstname": "robert",
      "lastname": "rodrigues"
    },
    "test2": {
      "email": "bill@mail.com",
      "firstname": "bill"
    },
    "test3": {
      "email": "bill@mail.com",
      "firstname": "bill"
    },
    "test4": {
      "edges": [
        {
          "node": {
            "email": "bill@mail.com",
            "firstname": "bill"
          }
        },
        {
          "node": {
            "email": "roberto@gmail.com",
            "firstname": "robert"
          }
        }
      ]
    },
    "test5": {
      "edges": [
        {
          "node": {
            "email": "bill@mail.com",
            "firstname": "bill"
          }
        },
        {
          "node": {
            "email": "roberto@gmail.com",
            "firstname": "robert"
          }
        }
      ]
    }
  }
}

TODO

  • create a temporary mongoDB service