Ошибка: может только создать список GraphQLType, но получил: функция GraphQLObjectType(config), в GraphQL?

Я работаю над демонстрационным проектом на GraphQL. Но застрял здесь. Я хочу отправить весь объект как результат. Объект, который я хочу отправить:

 exports.fakeDatabase = {
        1: {
            id: 1,
            name: 'Abhay',
            description:'This is Abhay\'s Database'
        },
        2: {
            id: 2,
            name:'Bankimchandra',
            description: 'This is Bankimchandra\'s Database'
        },
         3: {
            id: 3,
            name:'chandu',
            description: 'This is chandu\'s Database'
        }
    };

Но когда я отправляю запрос на доступ к нему, я получаю сообщение об ошибке:

Error: Can only create List of a GraphQLType but got: function GraphQLObjectType(config) {
    _classCallCheck(this, GraphQLObjectType);

    (0, _assertValidName.assertValidName)(config.name, config.isIntrospection);
    this.name = config.name;
    this.description = config.description;
    if (config.isTypeOf) {
      (0, _invariant2.default)(typeof config.isTypeOf === 'function', this.name + ' must provide "isTypeOf" as a function.');
    }
    this.isTypeOf = config.isTypeOf;
    this._typeConfig = config;
  }.

Мой код

schema.js:

const graphql = require('graphql');
var schema = {};
schema.getAllUser = new graphql.GraphQLObjectType({
    name: 'getAllUser',
    fields: {
        data:{type:new graphql.GraphQLList(graphql.GraphQLObjectType)}  // What should I do here to send the whole `fakeObject`
   }
})
module.exports = schema;

Query.js:

const graphql = require('graphql');
const userType = require('../schemas/schemaUserType');
const fakeDatabase = require('../assets/database');
const config = require('../config/config');


var schema = {};
module.exports = schema;
const queryType = new graphql.GraphQLObjectType({
    name: 'Query',
    fields: {
 getAllUser: {
            type: userType.getAllUser,
            args: {
            }, resolve: function () {
                return fakeDatabase.fakeDatabase;
            }
        }
    }
});
schema.queryTypq1 = new graphql.GraphQLSchema({ query: queryType });

server.js:

var app = require('express')();
var graphHTTP = require('express-graphql');
const schema = require('./queries/queryType');

app.use('/graphql', graphHTTP({
  schema: schema.queryTypq1,
  graphiql: true
}));

app.listen(4000, () => { console.log('Server is running on port: 4000'); });

Пожалуйста, дайте мне понять, что я должен сделать, чтобы отправить объект fakeDatabase

1 ответ

Решение
  1. Первый fakeDatabase должен быть массив [] как поле data тип имеет GraphQLList в schema.getAllUser

  2. Во-вторых, вы должны создать GraphQLObjectType с полями id, name а также description


может быть что-то вроде этого...

exports.fakeDatabase = [
    {
        id: 1,
        name: 'Abhay',
        description: 'This is Abhay\'s Database'
    },
    {
        id: 2,
        name: 'Bankimchandra',
        description: 'This is Bankimchandra\'s Database'
    },
    {
        id: 3,
        name: 'chandu',
        description: 'This is chandu\'s Database'
    }
]

и GraphQLObjectType для представления данных

const fakeDatabaseType = new GraphQLObjectType({
    name: 'fakeDatabase',
    fields: {
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        description: { type: GraphQLString },
    },
});


const graphql = require('graphql');
var schema = {};
schema.getAllUser = new graphql.GraphQLObjectType({
    name: 'getAllUser',
    fields: {
        data: {
            type: new graphql.GraphQLList(fakeDatabaseType),
            resolve: function (obj) { /* obj is the parent object 
containing the data passed from root query resolver */
                return obj;
            },
        }
    }
})
module.exports = schema;

const graphql = require('graphql');
const userType = require('../schemas/schemaUserType');
const fakeDatabase = require('../assets/database');
const config = require('../config/config');


var schema = {};
module.exports = schema;
const queryType = new graphql.GraphQLObjectType({
    name: 'Query',
    fields: {
        getAllUser: {
            type: schema.getAllUser,
            args: {
            }, resolve: function () {
                return fakeDatabase; // passing the fake array
            }
        }
    }
});
schema.queryTypq1 = new graphql.GraphQLSchema({ query: queryType });

Надеюсь это поможет!!

Другие вопросы по тегам