GraphQL Node.js server with MongoDB and Express

ref:

The GraphQL JS library provides a resolve function for the schemas:

user: {  
  type: userType,
  args: {
    id: {
      name: 'id',
      type: new GraphQLNonNull(GraphQLString)
    }
  },
  resolve: (root, {id}) => {
    return User.findById(id);
  }
}

The only thing what we have to do here is to provide the data for the specific resolve functions. These functions are called by GraphQL JS in parallel.

We can generate a projection for our MongoDB query in the following way:

function getProjection (fieldASTs) {  
  return fieldASTs.selectionSet.selections.reduce((projections, selection) => {
    projections[selection.name.value] = 1;

    return projections;
  }, {});
}

and use it like:

resolve: (root, {id}, source, fieldASTs) => {  
  var projections = getProjection(fieldASTs);
  return User.findById(id, projections);
}

This helps optimising the amount of the fetched data from our database.

Check out the Node.js implementation with MongoDB for more details: https://github.com/RisingStack/graphql-server

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s