Ошибка подписки GraphQL: аргумент \ "properties \" должен иметь тип Array. Объект полученного типа " - PullRequest
1 голос
/ 05 октября 2019

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

Я уже добавилподписку в схеме, я включил публикацию события в мутацию addUser и определил функцию подписки для типа подписки.

Теперь, когда я пытаюсь выполнить запрос подписки в graphiql в-browser IDE, я получаю эту ошибку:

Аргумент \ "properties \" должен иметь тип Array. Объект полученного типа "

Прикреплен объект схемы,Я что-то настроил неправильно или я что-то упустил? Спасибо!

PS Я также должен упомянуть, что я использую mongoose для хранения данных в экземпляре Монго, следовательно, сущности.

import {
    GraphQLFloat,
    GraphQLID,
    GraphQLInt,
    GraphQLList,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLString
} from 'graphql';
// models
import UserType from '../types/user/UserType';
import AccountType from '../types/account/AccountType';
import TransactionType from '../types/transaction/TransactionType';
// entities
import User from '../entities/user/user';
import Account from '../entities/account/account';
import Transaction from '../entities/transaction/transaction';
// subscriptions
import { PubSub } from 'graphql-subscriptions';

// subscriptions
const pubsub = new PubSub();
const USER_CREATED = 'user_created';

// the acceptable starting point of our graph
const RootQueryType = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: () => ({
        // query individual entities in the database
        user: {
            type: UserType,
            description: 'The current user identified by an id',
            args: {
                id: {
                    type: GraphQLID
                }
            },
            resolve(parent, args) {
                return User.findById(args.id);
            }
        },
        account: {
            type: AccountType,
            description: 'Details about the account in question identified by an id',
            args: {
                id: {
                    type: GraphQLID
                }
            },
            resolve(parent, args) {
                return Account.findById(args.id);
            }
        },
        transaction: {
            type: TransactionType,
            description: 'Details about the transaction in question identified by an id',
            args: {
                id: {
                    type: GraphQLID
                }
            },
            resolve(parent, args) {
                return Transaction.findById(args.id);
            }
        },
        // query all entities in the database
        users: {
            type: new GraphQLList(UserType),
            resolve: (parent, args) => {
                return User.find({});
            }
        },
        accounts: {
            type: new GraphQLList(AccountType),
            resolve: (parent, args) => {
                return Account.find({});
            }
        },
        transactions: {
            type: new GraphQLList(TransactionType),
            resolve(parent, args) {
                return Transaction.find({});
            }
        }
    })
});

const MutationType = new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
        addUser: {
            type: UserType,
            args: {
                name: {
                    type: new GraphQLNonNull(GraphQLString)
                },
                age: {
                    type: new GraphQLNonNull(GraphQLInt)
                },
                email: {
                    type: new GraphQLNonNull(GraphQLString)
                }
            },
            resolve(parent, args) {
                let user = new User({
                    name: args.name,
                    age: args.age,
                    email: args.email
                });
                pubsub.publish(USER_CREATED, {
                    newUser: user
                });
                return user.save();
            }
        },
        addAccount: {
            type: AccountType,
            args: {
                currency: {
                    type: new GraphQLNonNull(GraphQLString)
                },
                balance: {
                    type: new GraphQLNonNull(GraphQLFloat)
                },
                holderId: {
                    type: new GraphQLNonNull(GraphQLString)
                }
            },
            resolve(parent, args) {
                let account = new Account({
                    currency: args.currency,
                    balance: args.balance,
                    holderId: args.holderId
                });
                return account.save().then(() => console.log('user created'));
            }
        },
        addTransaction: {
            type: TransactionType,
            args: {
                sourceAccountId: {
                    type: new GraphQLNonNull(GraphQLString)
                },
                targetAccountId: {
                    type: new GraphQLNonNull(GraphQLString)
                },
                amount: {
                    type: new GraphQLNonNull(GraphQLFloat)
                }
            },
            resolve(parent, args) {
                let transaction = new Transaction({
                    sourceAccountId: args.sourceAccountId,
                    tagetAccountId: args.tagetAccountId,
                    timestamp: new Date(),
                    amount: args.amount
                });

                Account.findById(args.sourceAccountId, (err, account) => {
                    if (!err) {
                        account.balance -= args.amount;
                        return account.save();
                    }
                });

                Account.findById(args.targetAccountId, (err, account) => {
                    if (!err) {
                        account.balance += args.amount;
                        return account.save();
                    }
                });

                return transaction.save();
            }
        }
    })
});

const SubscriptionType = new GraphQLObjectType({
    name: 'Subscription',
    fields: () => ({
        newUser: {
            type: UserType,
            description: 'This subscription is going to provide information every time a new user creation event fires',
            resolve: (payload, args, context, info) => {
                console.table(payload, args, context, info); // debugging
                return payload;
            },
            subscribe: () => pubsub.asyncIterator(USER_CREATED)
        }
    })
});

const schema = new GraphQLSchema({
    query: RootQueryType,
    mutation: MutationType,
    subscription: SubscriptionType
});

export default schema;

Я ожидаючто когда я запускаю запрос на подписку, он запускает прослушивание публикуемых событий, а когда на другой вкладке я запускаю мутацию для добавления нового пользователя, первая вкладка будет перехватывать событие и возвращать сведения о пользователе в полезной нагрузке.

...