Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL: How do you pass args to to sub objects

Tags:

graphql

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;
like image 434
Fallfast Avatar asked Feb 25 '16 16:02

Fallfast


People also ask

How do you pass an argument in GraphQL query?

When you're passing arguments in code, it's generally better to avoid constructing the whole query string yourself. Instead, you can use $ syntax to define variables in your query, and pass the variables as a separate map. . then(data => console.

How do you pass multiple arguments in GraphQL query?

Multiple arguments can be used together in the same query. For example, you can use the where argument to filter the results and then use the order_by argument to sort them.

How do you pass variables in GraphiQL?

Variables should be written using the JSON format. Therefore if you add for example a comma at the end of the last attribute, the GraphiQL invalidates the object with the variables.

What is the second argument passed into GraphQL resolvers?

To access this id , we can use the second parameter in the resolver: args . args is an object that contains all GraphQL arguments that were provided for the field. We can destructure this object to access the id property, then pass that id into our getTrack method. Then, we can return the results of that method.


1 Answers

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();.

like image 199
Nish Avatar answered Oct 24 '22 17:10

Nish