Resolve relations

Let's see how graphql-thinky allow us to query related types:
ex: Users has many tasks

  • You must to set the relations on the targeted models.
  • You must reference the relation name on the resolve function

Models

Let's create our 2 models, User - Task

// Models.js
import thinky from '../thinky';
const type = thinky.type;

// User Model
const User = thinky.createModel('user', {
  name: type.string()
});

User.relations = () => {
  User.hasMany(thinky.models.task,'tasks','id','user_id');
}

export User;

// Task Model
const Task = thinky.createModel('task', {
  text: type.string(),
  completed: type.boolean(),
  user_id: type.string().allowNull(false)
});

Task.relations = () => {
  Task.belongsTo(thinky.models.user,'user','user_id','id');
}

export Task;

GQL Object Types

When creating object type we can pass the fields option to extend the shape of the final type.
We do as such to include our new tasks node to the UserType.

The resolve function will now accept a second argument which is the relation name of the user model. It will automatically resolve as a join instruction to thinky.

//UserType.js
import taskType from './taskType';
import GT from './graphql-thinky';

const { resolve } = GT;

const UserType = GT.createModelType('user', {
	fields: () => ({
  	tasks: {
    	type: taskType,
      resolve: resolve('user','tasks')
  })
});
// TaskType.js
import userType from './userType';
import GT from './graphql-thinky';

const { resolve } = GT;

export default GT.createModelType('task', {
	fields: () => ({
  	tasks: {
    	type: userType,
      resolve: resolve('task','user') // task belongs to user
  })
});

You can still use the 3rd argument to provide custom filtering.