GraphQL Args error: argument type must be Input Ty

2019-03-19 04:22发布

问题:

On server start (node index.js) I am getting the following error with my GraphQL NodeJS server:

Error: Query.payment(data:) argument type must be Input Type but got: function GraphQLObjectType(config) { _classCallCheck(this, GraphQLObjectType);

This error happened when I changed my original args from a string

        args: {
            data: { type: graphQL.GraphQLString }
        },

To an object type:

        args: {
            data: { type: graphQL.GraphQLObjectType }
        },

I need an object type as I need to send several fields as params.

GraphQL Server:

var Query = new graphQL.GraphQLObjectType({
    name: 'Query',
    fields: {
        payment: {
            type: graphQL.GraphQLString,
            args: {
                data: { type: graphQL.GraphQLObjectType }
            },
            resolve: function (_, args) {
                // There will be more data here, 
                // but ultimately I want to return a string
                return 'success!';
            }
        }
    }
});

How can I allow it to accept an object?


Frontend (if needed. But the error is happening before I even send this):

var userQuery = encodeURIComponent('{ payment ( data: { user : "test" } )}');

$.get('http://localhost:4000/graphql?query=' + userQuery, function (res) {
       //stuff
});

回答1:

If you want use Object as an argument, you should use GraphQLInputObjectType instead of GraphQLObjectType. And keep in mind that GraphQL is strongly type based, so you're not allowed to use a generic GraphQLObjectType as arg type and then dynamically query args. You have to explicitly define all possible fields in this input object (and choose which of them would be mandatory and which not)

Try use this approach:

// your arg input object
var inputType = new GraphQLInputObjectType({
    name: 'paymentInput',
    fields: {
        user: {
            type: new GraphQLNonNull(GraphQLString)
        },
        order: {
            type: GraphQLString
        },
        ...another fields
    }
});

var Query = new graphQL.GraphQLObjectType({
    name: 'Query',
    fields: {
        payment: {
            type: graphQL.GraphQLString,
            args: {
                data: { type: new GraphQLNonNull(inputType) }
            },
            resolve: function (_, args) {
                // There will be more data here,
                // but ultimately I want to return a string
                return 'success!';
            }
        }
    }
});