subscriptionClient.subscribe не является функцией - PullRequest
0 голосов
/ 18 апреля 2019

В этом случае я просто пытаюсь запустить фиктивную подписку, используя graphql-подписки, а позже интегрировать ее в мой код.Однако, даже с минимальным примером.

Я следую примеру scotch.io, вот его ссылка git https://github.com/kimobrian/GraphQL-Express/tree/subscriptions

, он выдает ошибку при подписке в graphiql

subscriptionClient.subscribe не является функцией

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

Следуя некоторым советам пов сети у меня даже понижена версия subscription-transport-ws с 0.9 до 0.8.3

У меня запущены запросы и мутации, но подписка выбрасывает вышеупомянутую ошибку в Graphiql

Файл сервера

import express from 'express';
import {
  graphqlExpress,
  graphiqlExpress,
} from 'graphql-server-express';
import bodyParser from 'body-parser';
import cors from 'cors';

import { schema } from './src/schema';

import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';

const PORT = 7900;
const server = express();

server.use('*', cors({ origin: 'http://localhost:3000' }));

server.use('/graphql', bodyParser.json(), graphqlExpress({
  schema
}));

server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
  subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`
}));

// We wrap the express server so that we can attach the WebSocket for subscriptions
const ws = createServer(server);

ws.listen(PORT, () => {
  console.log(`GraphQL Server is now running on http://localhost:${PORT}`);

  // Set up the WebSocket for handling GraphQL subscriptions
  new SubscriptionServer({
    execute,
    subscribe,
    schema
  }, {
    server: ws,
    path: '/subscriptions',
  });
});

package.json

{
  "name": "tutorial-server",
  "version": "1.0.0",
  "description": "A simple GraphQL server",
  "main": "server.js",
  "scripts": {
    "start": "nodemon ./server.js --exec babel-node -e js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.24.0",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-stage-0": "^6.22.0",
    "nodemon": "^1.11.0"
  },
  "dependencies": {
    "body-parser": "^1.17.1",
    "cors": "^2.8.3",
    "express": "^4.15.2",
    "graphql": "^0.11.3",
    "graphql-server-express": "^1.1.2",
    "graphql-subscriptions": "^0.5.1",
    "graphql-tools": "^1.2.3",
    "subscriptions-transport-ws": "0.8.3"
  }
}

Схема

import {
  makeExecutableSchema
} from 'graphql-tools';

import { resolvers } from './resolvers';

const typeDefs = `
type Channel {
  id: ID!                # "!" denotes a required field
  name: String
}

type Message {
  id: ID!
  text: String
}

# This type specifies the entry points into our API
type Query {
  channels: [Channel]    # "[]" means this is a list of channels
  channel(id: ID!): Channel
}

# The mutation root type, used to define all mutations
type Mutation {
  addChannel(name: String!): Channel
}

# The subscription root type, specifying what we can subscribe to
type Subscription {
    channelAdded: Channel
}
`;

const schema = makeExecutableSchema({ typeDefs, resolvers });
export { schema };

Resolver

import { PubSub } from 'graphql-subscriptions';

const channels = [{
  id: 1,
  name: 'soccer',
}, {
  id: 2,
  name: 'baseball',
}];

let nextId = 3;
const CHANNEL_ADDED_TOPIC = 'newChannel';
const pubsub = new PubSub();

export const resolvers = {
  Query: {
    channels: () => {
      return channels;
    },
    channel: (root, { id }) => {
      return channels.find(channel => channel.id === id);
    },
  },
  Mutation: {
    addChannel: (root, args) => {
      const newChannel = { id: String(nextId++), messages: [], name: args.name };
      channels.push(newChannel);
      pubsub.publish(CHANNEL_ADDED_TOPIC, { channelAdded: newChannel });
      return newChannel;
    }
  },
  Subscription: {
    channelAdded: {
      subscribe: () => pubsub.asyncIterator(CHANNEL_ADDED_TOPIC)
    }
  }
};

Я ожидаю, что он должен обновиться в окне подписки, когда pubsub.publish хит

...