GraphQL error: Expected GraphQL named type but got: {} - graphql

I have 2 custom graphql types, entityType and containerType, where 1 container can have multiple entities.
So, I am binding all the entities with their respective containers via this code:
const graphql = require('graphql')
const _ = require('lodash')
const UserType = require('./userSchema')
const ContainerType = require('./containerSchema')
const Container = require('../models/container')
const Entity = require('../models/entity')
const {
GraphQLObjectType,
GraphQLString,
GraphQLBoolean,
GraphQLSchema,
GraphQLInt,
GraphQLID,
GraphQLList,
GraphQLNonNull,
GraphQLUnionType
} = graphql
const EntityType = new GraphQLObjectType({
name: "Entity",
fields: () => ({
name: { type: new GraphQLNonNull(GraphQLString) },
container: {
type: ContainerType,
resolve: function(parent, args) {
return Container.findById(parent.containerId)
}
},
type: { type: new GraphQLNonNull(GraphQLString) },
detail: { type: new GraphQLNonNull(GraphQLString) },
start: { type: GraphQLString },
end: { type: GraphQLString }
})
})
module.exports = { EntityType }
I am quite sure that containerType is working, because I am using it is being used on other places and is working well. Here is the code for Container type:
const graphql = require('graphql')
const _ = require('lodash')
const UserType = require('./userSchema')
const { EntityType } = require('./entitySchema')
const User = require('../models/user')
const Container = require('../models/container')
const Entity = require('../models/entity')
const {
GraphQLObjectType,
GraphQLString,
GraphQLBoolean,
GraphQLSchema,
GraphQLInt,
GraphQLID,
GraphQLList,
GraphQLNonNull
} = graphql
const ContainerType = new GraphQLObjectType ({
name: 'Container',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
user: {
type: UserType,
resolve: function (parent, args) {
return User.findById(parent.userId)
}
},
parent: {
type: ContainerType,
resolve: function (parent, args) {
return Container.findById(parent.parentContainer)
}
},
detail: { type: GraphQLString },
start: { type: GraphQLString },
end: { type: GraphQLString },
createdAt: { type: GraphQLString },
category: { type: GraphQLString },
status: { type: GraphQLString },
entities: {
type: GraphQLList(EntityType),
resolve: async function(parent, args) {
return await Entity.find({ containerId: parent.id })
}
}
})
})
module.exports = ContainerType
no error is shown on the terminal, but the Graphiql console shows following error when loading up:
{
"errors": [
{
"message": "The type of Entity.container must be Output Type but got: {}."
},
{
"message": "Expected GraphQL named type but got: {}."
}
]
}

I figured out that the problem was with something called "module cycles". this post was very helpful to resolve it.
Finally, I ended up adding both EntitySchema and ContainerSchema in a single file, here is the code:
const graphql = require('graphql')
const _ = require('lodash')
const UserType = require('./userSchema')
const User = require('../models/user')
const Container = require('../models/container')
const Entity = require('../models/entity')
const {
GraphQLObjectType,
GraphQLString,
GraphQLBoolean,
GraphQLInt,
GraphQLID,
GraphQLList,
GraphQLNonNull
} = graphql
const EntityType = new GraphQLObjectType ({
name: "Entity",
fields: () => ({
name: { type: new GraphQLNonNull(GraphQLString) },
container: {
type: ContainerType,
resolve: (parent, args) => {
return Container.findById(parent.containerId)
}
},
type: { type: new GraphQLNonNull(GraphQLString) },
detail: { type: new GraphQLNonNull(GraphQLString) },
start: { type: GraphQLString },
end: { type: GraphQLString }
})
})
const ContainerType = new GraphQLObjectType ({
name: 'Container',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
user: {
type: UserType,
resolve: function (parent, args) {
return User.findById(parent.userId)
}
},
parent: {
type: ContainerType,
resolve: function (parent, args) {
return Container.findById(parent.parentContainer)
}
},
detail: { type: GraphQLString },
start: { type: GraphQLString },
end: { type: GraphQLString },
createdAt: { type: GraphQLString },
category: { type: GraphQLString },
status: { type: GraphQLString },
entities: {
type: GraphQLList(EntityType),
resolve: async function(parent, args) {
return await Entity.find({ containerId: parent.id })
}
}
})
})
module.exports = {
EntityType,
ContainerType
}

Related

How to implement interface using GraphQL and node

I want to achieve the fields of one object type within another object type
Here is my schema file.
const Films = new GraphQLInterfaceType({
name: 'films',
fields: () => ({
id:{
type: GraphQLID
},
name: {
type: GraphQLString,
},
})
})
const MovieStream = new GraphQLObjectType({
name: 'MovieStream',
interfaces: () => [Films],
fields: () => ({
id: {
type: GraphQLID,
},
movie_id: {
type: GraphQLString,
},
})
})
Here I am trying to use the interface. But It shows error:
{
"errors": [
{
"message": "Query root type must be Object type, it cannot be { __validationErrors: undefined, __allowedLegacyNames: [], _queryType: undefined, _mutationType: undefined, _subscriptionType: undefined, _directives: [#include, #skip, #deprecated], astNode: undefined, extensionASTNodes: undefined, _typeMap: { __Schema: __Schema, __Type: __Type, __TypeKind: __TypeKind, String: String, Boolean: Boolean, __Field: __Field, __InputValue: __InputValue, __EnumValue: __EnumValue, __Directive: __Directive, __DirectiveLocation: __DirectiveLocation, films: films, ID: ID, Date: Date, JSON: JSON, MovieStream: MovieStream }, _possibleTypeMap: {}, _implementations: { films: [] } }."
},
{
"message": "Expected GraphQL named type but got: { __validationErrors: undefined, __allowedLegacyNames: [], _queryType: undefined, _mutationType: undefined, _subscriptionType: undefined, _directives: [#include, #skip, #deprecated], astNode: undefined, extensionASTNodes: undefined, _typeMap: { __Schema: __Schema, __Type: __Type, __TypeKind: __TypeKind, String: String, Boolean: Boolean, __Field: __Field, __InputValue: __InputValue, __EnumValue: __EnumValue, __Directive: __Directive, __DirectiveLocation: __DirectiveLocation, films: films, ID: ID, Date: Date, JSON: JSON, MovieStream: MovieStream }, _possibleTypeMap: {}, _implementations: { films: [] } }."
}
]
}
Here is Query type:
const QueryRoot = new GraphQLObjectType({
name: 'Query',
fields: () => ({
getContentList:{
type: new GraphQLList(contentCategory),
args: {
id: {
type: GraphQLInt
},
permalink: {
type: GraphQLString
},
language: {
type: GraphQLString
},
content_types_id: {
type: GraphQLString
},
oauth_token:{
type: GraphQLString
}
},
resolve: (parent, args, context, resolveInfo) => {
var category_flag = 0;
var menuItemInfo = '';
user_id = args.user_id ? args.user_id : 0;
// console.log("context"+context['oauth_token']);
return AuthDb.models.oauth_registration.findAll({attributes: ['oauth_token', 'studio_id'],where:{
// oauth_token:context['oauth_token'],
$or: [
{
oauth_token:
{
$eq: context['oauth_token']
}
},
{
oauth_token:
{
$eq: args.oauth_token
}
},
]
},limit:1}).then(oauth_registration => {
var oauthRegistration = oauth_registration[0]
// for(var i = 0;i<=oauth_registration.ength;i++){
if(oauth_registration && oauthRegistration && oauthRegistration.oauth_token == context['oauth_token'] || oauthRegistration.oauth_token == args.oauth_token){
studio_id = oauthRegistration.studio_id;
return joinMonster.default(resolveInfo,{}, sql => {
return contentCategoryDb.query(sql).then(function(result) {
return result[0];
});
} ,{dialect: 'mysql'});
}else{
throw new Error('Invalid OAuth Token');
}
})
},
where: (filmTable, args, context) => {
return getLanguage_id(args.language).then(language_id=>{
return ` ${filmTable}.permalink = "${args.permalink}" and ${filmTable}.studio_id = "${studio_id}" and (${filmTable}.language_id = "${language_id}" OR ${filmTable}.parent_id = 0 AND ${filmTable}.id NOT IN (SELECT ${filmTable}.parent_id FROM content_category WHERE ${filmTable}.permalink = "${args.permalink}" and ${filmTable}.language_id = "${language_id}" and ${filmTable}.studio_id = "${studio_id}"))`
})
},
}
})
})
module.exports = new GraphQLSchema({
query: QueryRoot
})
Please help me out. have i done something wrong in the use of interface?
I have found the answer through this post
Is it possible to fetch data from multiple tables using GraphQLList
Anyone please tell me the exact way to use the interface in my code.
Although the error you have printed does not really relate to interfaces implementations, in order for you to use interfaces, you have to implement the methods/types the interface references. So in your situation your object MovieStream is missing the type name that you refer in the object Films.
Your code should look something like:
const Films = new GraphQLInterfaceType({
name: 'films',
fields: () => ({
id:{
type: GraphQLID
},
name: {
type: GraphQLString,
},
})
})
const MovieStream = new GraphQLObjectType({
name: 'MovieStream',
interfaces: () => [Films],
fields: () => ({
id: {
type: GraphQLID,
},
name: {
type: GraphQLString // You're missing this!
},
movie_id: {
type: GraphQLString,
},
})
})
Now back to the error you have printed "message": "Query root type must be Object type, it cannot be...
This seems to be related to your QueryRoot object, it seems that GraphQLSchema is not recognizing the root object. If this issue is still there once you fix the interface, have a look at this answer here

Modularizing GraphQL Types into separate files

I have a GraphQL implementation with a single monolithic types/index.js file that currently contains two type definitions:
const graphql = require('graphql');
const Book = require('../../../models/book');
const Author = require('../../../models/author');
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
} = graphql;
const BookType = new GraphQLObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
author: {
type: AuthorType,
resolve: (parent, args) => {
// code to get data from db
return Author.findById(parent.authorId);
},
},
}),
});
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve: (parent, args) => {
// code to get data from db
return Book.find({authorId: parent.id});
},
},
}),
});
module.exports = {BookType, AuthorType};
This is the file I import into my schema.js file where it's used by root queries and mutations:
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
} = require('graphql');
const Book = require('../../../models/book');
const Author = require('../../../models/author');
const {BookType, AuthorType} = require('../types');
// QUERIES
//------------------------------------------------------------------------------------------------------
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLID } },
resolve: (parent, args) => {
// code to get data from db
return Book.findById(args.id);
},
},
author: {
type: AuthorType,
args: { id: { type: GraphQLID } },
resolve: (parent, args) => {
// code to get data from db
return Author.findById(args.id);
},
},
books: {
type: new GraphQLList(BookType),
resolve: (parent, args) => {
// code to get data from db
return Book.find({});
},
},
authors: {
type: new GraphQLList(AuthorType),
resolve: (parent, args) => {
// code to get data from db
return Author.find({});
}
},
},
});
// MUTATIONS
//------------------------------------------------------------------------------------------------------
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addAuthor: {
type: AuthorType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
age: { type: new GraphQLNonNull(GraphQLInt) }
},
resolve(parent, args) {
let author = new Author({
name: args.name,
age: args.age
});
return author.save();
}
},
addBook: {
type: BookType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
genre: { type: new GraphQLNonNull(GraphQLString) },
authorId: { type: new GraphQLNonNull(GraphQLID) },
},
resolve(parent, args) {
let book = new Book({
name: args.name,
genre: args.genre,
authorId: args.authorId,
});
return book.save();
},
},
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation,
});
But as the project grows, I am anticipating dozens of types with tons of two-way relationships. So I'd like to modularize all my types into individual files, such as types/BookType.js, types/AuthorType.js, etc. rather than a single types/index.js as I have right now. What's the best way to accomplish this given the two-way relationships?
While segregating the types into separate files, you'll need to handle two-way relationships. In this case, AuthorType needs BookType and vice-versa. So you'll need to import AuthorType in types/BookTypes.js and BookType in types/AuthorType.js but this will introduce a classic circular dependency issue (before AuthorType exports it demands BookType and vice-versa) which is common in node projects. You can read more about it here. To handle this, shift your require calls at the end of the file in both types. So your code looks somewhat like this:
types/BookType.js
const graphql = require('graphql');
const Book = require('../../../models/book');
const Author = require('../../../models/author');
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
} = graphql;
const BookType = new GraphQLObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
author: {
type: AuthorType,
resolve: (parent, args) => {
// code to get data from db
return Author.findById(parent.authorId);
},
},
}),
});
module.exports = BookType;
// This is here to prevent circular dependencies problem which will lead to the formation of infinite loop
const AuthorType = require("./AuthorType");
types/AuthorType.js
const graphql = require('graphql');
const Book = require('../../../models/book');
const Author = require('../../../models/author');
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
} = graphql;
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
id: {
type: GraphQLID
},
name: {
type: GraphQLString
},
age: {
type: GraphQLInt
},
books: {
type: new GraphQLList(BookType),
resolve: (parent, args) => {
// code to get data from db
return Book.find({
authorId: parent.id
});
},
},
}),
});
module.exports = AuthorType;
// This is here to prevent circular dependencies problem which will lead to the formation of infinite loop
const BookType = require("./BookType");
Also, it is better to have a types/index.js which will act as a handler for import/exports. You export every type to index.js and take whatever you want from it anywhere. This saves you from a lot of messy code because now you can do something like this:
const { BookType, AuthorType, OtherType } = require("../types/index");

Error: Expected [object Object] to be a GraphQL type

This code was working until I added the Resources part into the code. It is similar to the other two so I am not sure why isn't it working.
Thanks in advance
Update:-
After using the debugger, I came to understand that the problem is in the RootQueryType.js and files associated with it as the error pops up when I am trying to export the schema and exactly at the query:RootQueryType place but still can't pinpoint at the error.
Update:-
I have put the schema.js file too in the end
resourceType.js
const graphql = require("graphql");
const UserType = require("./userType");
const User = require("../models/User");
const Project = require("../models/Project");
const Resource = require("../models/Resource");
const ProjectType = require("./projectType");
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
} = graphql;
const ResourceType = new GraphQLObjectType({
name: "ResourceType",
fields: () => ({
id: { type: GraphQLString },
title: { type: GraphQLString },
url: { type: GraphQLString },
project:{
type:ProjectType,
resolve(parentValues,args){
return Project.findById(parentValues.id).populate("resources")
}
}
})
});
module.exports=ResourceType;
RootQueryType.js
const mongoose = require('mongoose');
const graphql = require('graphql');
const { GraphQLObjectType, GraphQLList, GraphQLID, GraphQLNonNull } = graphql;
const ProjectType = require('./../types/projectType');
const UserType = require('./../types/userType');
const Project=require("../models/Project");
const User=require("../models/User");
const RootQuery=new GraphQLObjectType({
name:"RootQueryType",
fields: () => ({
projects:{
type:new GraphQLList(ProjectType),
resolve(parentValues,args,request){
return Project.find().populate("contributors").populate("resources");
}
},
project:{
type:ProjectType,
args:{id:{type:new GraphQLNonNull(GraphQLID)}},
resolve(parentValue,args,request){
return Project.findById(args.id).populate("contributors").populate("resources");
}
},
users:{
type:new GraphQLList(UserType),
resolve(parentValues,args,request){
return User.find().populate("projects");
}
},
user:{
type:UserType,
args:{id:{type:new GraphQLNonNull(GraphQLID)}},
resolve(parentValue,args,request){
return User.findById(args.id).populate("projects")
}
},
})
})
module.exports = RootQuery;
Mutation.js
const mongoose = require("mongoose");
const ProjectType = require("./../types/projectType");
const UserType = require("./../types/userType");
const graphql = require("graphql");
const {
GraphQLObjectType,
GraphQLList,
GraphQLID,
GraphQLNonNull,
GraphQLString
} = graphql;
const Project = require("../models/Project");
const User = require("../models/User");
const mutation = new GraphQLObjectType({
name: "mutation",
fields: () => ({
addUser: {
type: UserType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
username: { type: new GraphQLNonNull(GraphQLString) },
password: { type: new GraphQLNonNull(GraphQLString) },
email: { type: new GraphQLNonNull(GraphQLString) },
githubProfile: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parentValues, args, request) {
return User.create(args);
}
},
addProject: {
type: ProjectType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
description: { type: new GraphQLNonNull(GraphQLString) },
image: { type:GraphQLString },
// contributor:{ type: new GraphQLNonNull(new GraphQLList(GraphQLID))
contributor:{ type: new GraphQLNonNull(GraphQLID)
},
},
resolve(parentValues, args, request) {
return Project.create(args);
}
}
})
});
module.exports = mutation;
I am positive it isnt the problem with other types because they were working earlier and I only added the .populate("resources") property to the resolve function of both of them. But just in case I am adding the code for them too.
userType.js
const graphql = require("graphql");
const ProjectType = require("./projectType");
const { GraphQLObjectType, GraphQLString, GraphQLList } = graphql;
const UserType = new GraphQLObjectType({
name: "User",
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString },
githubProfile: { type: GraphQLString },
username: { type: GraphQLString },
password: { type: GraphQLString },
email: { type: GraphQLString },
projects: {
type: new GraphQLList(ProjectType),
resolve(parentValues, args) {
return User.findById(parentValues.id).populate("projects");
}
}
})
});
module.exports = UserType;
and the other is
projectType.js
const graphql = require("graphql");
const UserType = require("./userType");
const ResourceType = require("./resourceType");
const User = require("../models/User");
const Project = require("../models/Project");
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
} = graphql;
const ProjectType = new GraphQLObjectType({
name: "ProjectType",
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString },
description: { type: GraphQLString },
image: { type: GraphQLString },
contributors: {
type: new GraphQLList(UserType),
resolve(parentValues, args, request) {
return Project.findContributors(parentValues.id);
}
},
resources:{
type: new GraphQLList(ResourceType),
resolve(parentValues, args, request) {
return Project.findResources(parentValues.id);
}
}
})
});
module.exports=ProjectType;
schema.js
const graphql = require("graphql");
const RootQuery = require("./RootQueryType");
const Mutation = require("./Mutation");
const { GraphQLSchema } = graphql;
console.log(RootQuery,Mutation);
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
});
Update:- I have removed the resources files and I am still getting the same error so it must be between user and project types
Update:-I finally tracked down the bug to being in the type files of both project and user type and it is being caused by the new GraphQLList, I still havent solved the error but removing it seems to make the error go away, no idea why.
Finally solved the problem, it was as #cito said, because of circular dependencies that was the cause of the error, that is as my UserType is dependent on ProjectType and likewise and hence I was getting this error, this was solved by
const graphql = require("graphql");
const User = require("../models/User");
const Project = require("../models/Project");
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
} = graphql;
const ProjectType = new GraphQLObjectType({
name: "ProjectType",
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString },
description: { type: GraphQLString },
image: { type: GraphQLString },
contributors: {
type: new GraphQLList(UserType),
resolve(parentValues, args, request) {
return Project.findContributors(parentValues.id);
}
},
resources:{
type: new GraphQLList(ResourceType),
resolve(parentValues, args, request) {
return Project.findResources(parentValues.id);
}
}
})
});
module.exports=ProjectType;
// This is here to prevent circular dependencies problem which will lead to the formation of infinite loop
const UserType = require("./userType");
const ResourceType = require("./resourceType");
that is requiring the files at the bottom
Your problem is the cyclic dependency between the userType and projectType module. Therefore the const value is still an empty object when it is passed to GraphQLList.
As a solution, you can move all the types into one module. Or, when exporting your classes, set them as properties of module.exports. This will work since you defined the fields properly as thunks.
By the way, you don't need the new when creating a GraphQLList or GraphQLNonNull wrapper. But that's not why you're getting the error.
Another way to go is:
resources:{
// require directly without creating a new variable
type: new GraphQLList(require("./resourceType")),
resolve(parentValues, args, request) {
return Project.findResources(parentValues.id);
}
}
I solved the problem. Just have both objectType in the same file.
I works

Why is this GraphQL query returning null? [duplicate]

This question already has answers here:
Why does a GraphQL query return null?
(6 answers)
Closed 3 years ago.
Schema:
const graphql = require('graphql');
const _ = require('lodash');
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema
} = graphql;
const users = [
{ id: '23', firstName: 'Bill', age: 20 },
{ id: '47', firstName: 'Samantha', age: 21 }
]
const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLString },
firstName: { type: GraphQLString },
age: {type: GraphQLInt },
}
});
const RootQueryType = new GraphQLObjectType({
name: 'RootQuery',
fields: {
user: {
type: UserType,
args: { id: {type: GraphQLString} },
resolve(parentValue, args) {
return _.find(users, args.id);
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQueryType,
});
Express:
const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema')
const app = express();
app.use('/graphql', expressGraphQL({
schema,
graphiql: true,
}));
app.listen(4000, () => {
console.log('Listening');
});
Query:
{
user(id:"23") {
id,
firstName,
age
}
}
Trying to learn GraphQL and can't for the life of me figure out what's wrong with my query/schema.
You just need to change how you're calling lodash's find:
return _.find(users, { id: args.id });

GraphQL: How do you pass args to to sub objects

I am using GraphQL to query an object that will be composed from about 15 different REST calls. This is my root query in which I pass in in the ID from the query. This works fine for the main student object that resolves correctly. However, I need to figure out how to pass the ID down to the address resolver. I tried adding args to the address object but I get an error that indicates that the args are not passed down from the Student object. So my question is: How do I pass arguments from the client query to sub objects in a GraphQL server?
let rootQuery = new GraphQLObjectType({
name: 'Query',
description: `The root query`,
fields: () => ({
Student : {
type: Student ,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (obj, args, ast) => {
return Resolver(args.id).Student();
}
}
})
});
export default rootQuery;
This is my primary student object that I link the other objects. In this case I have attached the ADDRESS object.
import {
GraphQLInt,
GraphQLObjectType,
GraphQLString,
GraphQLNonNull,
GraphQLList
} from 'graphql';
import Resolver from '../../resolver.js'
import iAddressType from './address.js'
let Student = new GraphQLObjectType({
name: 'STUDENT',
fields: () => ({
SCHOOLCODE: { type: GraphQLString },
LASTNAME: { type: GraphQLString },
ACCOUNTID: { type: GraphQLInt },
ALIENIDNUMBER: { type: GraphQLInt },
MIDDLEINITIAL: { type: GraphQLString },
DATELASTCHANGED: { type: GraphQLString },
ENROLLDATE: { type: GraphQLString },
FIRSTNAME: { type: GraphQLString },
DRIVERSLICENSESTATE: { type: GraphQLString },
ENROLLMENTSOURCE: { type: GraphQLString },
ADDRESSES: {
type: new GraphQLList(Address),
resolve(obj, args, ast){
return Resolver(args.id).Address();
}}
})
});
Here is my address object that is resolved by a second REST call:
let Address = new GraphQLObjectType({
name: 'ADDRESS',
fields: () => ({
ACTIVE: { type: GraphQLString },
ADDRESS1: { type: GraphQLString },
ADDRESS2: { type: GraphQLString },
ADDRESS3: { type: GraphQLString },
CAMPAIGN: { type: GraphQLString },
CITY: { type: GraphQLString },
STATE: { type: GraphQLString },
STATUS: { type: GraphQLString },
TIMECREATED: { type: GraphQLString },
TYPE: { type: GraphQLString },
ZIP: { type: GraphQLString },
})
});
export default Address;
These are my resolver
var Resolver = (id) => {
var options = {
hostname: "myhostname",
port: 4000
};
var GetPromise = (options, id, path) => {
return new Promise((resolve, reject) => {
http.get(options, (response) => {
var completeResponse = '';
response.on('data', (chunk) => {
completeResponse += chunk;
});
response.on('end', () => {
parser.parseString(completeResponse, (err, result) => {
let pathElements = path.split('.');
resolve(result[pathElements[0]][pathElements[1]]);
});
});
}).on('error', (e) => { });
});
};
let Student= () => {
options.path = '/Student/' + id;
return GetPromise(options, id, 'GetStudentResult.StudentINFO');
}
let Address= () => {
options.path = '/Address/' + id + '/All';
return GetPromise(options, id, 'getAddressResult.ADDRESS');
};
return {
Student,
Address
};
}
export default Resolver;
ADDRESSES: {
type: new GraphQLList(Address),
resolve(obj, args, ast){
return Resolver(args.id).Address();
}
}
args passed to ADDRESSES are arguments passed to ADDRESSES field at query time. In the resolve method, obj should be the student object and if you have an id property on it, all you need to do is: return Resolver(obj.id).Address();.

Resources