Uses GraphQL resolve's info to generate mongoDB projections
Supports:
- Fields
- InlineFragments
- FragmentSpreads
- Relay Edge Node Pattern
references:
$ 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))
}
}
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": "[email protected]",
"firstname": "robert",
"lastname": "rodrigues"
},
"test2": {
"email": "[email protected]",
"firstname": "bill"
},
"test3": {
"email": "[email protected]",
"firstname": "bill"
},
"test4": {
"edges": [
{
"node": {
"email": "[email protected]",
"firstname": "bill"
}
},
{
"node": {
"email": "[email protected]",
"firstname": "robert"
}
}
]
},
"test5": {
"edges": [
{
"node": {
"email": "[email protected]",
"firstname": "bill"
}
},
{
"node": {
"email": "[email protected]",
"firstname": "robert"
}
}
]
}
}
}
- create a temporary mongoDB service