Skip to content
This repository has been archived by the owner on Dec 2, 2017. It is now read-only.

Creating a resolver

Sergio Xalambrí edited this page Jul 25, 2017 · 1 revision

A resolver it's a function which match your schema to allow you to run queries, mutations or subscriptions. You can exports a single object with your whole resolvers map or devide it (recommended) in multiple exports and files.

// main resolvers
exports.Query = {
  me(rootQuery, args, context) {
    return context.models.User.me();
  },
};

// type resolvers
exports.User = {
  fullName(user) {
    return `${user.firstName} ${user.lastName}`;
  },
};

That's the resolvers.js from the basic example, as you can observe we exported two objects, the schema Query resolvers map and the User type resolvers map. Each object has method that match your schema definition.

That example use a single file, but if your resolvers map grow you can split it in multiple files for each type definition and then write something like this.

exports.User = require('./resolvers/User.js')

That way your ./resolvers/User.js file can have the methods required to resolver the full User type.

Testing

Because the resolvers receive the models and connectors from the context object you can easily test it, if you have a resolver like this:

exports.posts = function posts(user, args, context) {
  return context.connectors.rest.read({
    resource: 'posts',
    params: { userId: user.id },
  });
};

exports.todos = function todos(user, args, context) {
  return context.connectors.rest.read({
    resource: 'todos',
    params: { userId: user.id },
  });
};

exports.albums = function albums(user, args, context) {
  return context.connectors.rest.read({
    resource: 'albums',
    params: { userId: user.id },
  });
};

From the jsonplaceholder-wrapper example

You can import each method and test them individually injecting the connectors or models.

const { posts } = require('./User.js');

describe('User resolver', () => {
  it('should fetch the posts of a user', () => {
    const posts = [{ id: 1 }, { id: 2 }, { id: 3 }];

    expect(posts({ id: 1 }), null, {
      connectors: {
        Rest: {
          read({ resource, params }) {
            expect(resource).toBe('posts');
            expect(params.userId).toBe(1);
            return posts;
          },
        },
      },
    }).toBe(posts);
  });
});

That way you can be sure your resolvers code run without problems.