我使用Apollo Server,Sequelize(针对ORM),MySQL(DB)和Express(Web Server)制作了GraphQL后端。
我还添加了订阅,其中存在问题。 我甚至无法使用websocket测试仪访问WS端点。
有人可以查看我的代码并告诉我问题是什么吗?我查看了文档,其他stackoverflow问题,我找不到任何解决方案。
代码:https://github.com/seklyza/graphqlsubscriptions
谢谢大家
答案 0 :(得分:0)
我认为你必须为使用express
服务器的应用程序和一个用于websocket的应用程序创建一个服务器。它可能看起来像这样。
GraphQL express服务器:
...
graphQLServer = express();
const GRAPHQL_PORT = 4000;
graphQLServer.use('/graphql', bodyParser.json(), graphqlExpress((request) => {
return {
schema: executableSchema,
};
}));
graphQLServer.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
graphQLServer.listen(GRAPHQL_PORT, () => {
console.log(`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`); // eslint-disable-line no-console
});
...

用于订阅的websocket服务器:
...
const WS_PORT = 8080;
const websocketServer = createServer((request, response) => {
response.writeHead(404);
response.end();
});
websocketServer.listen(WS_PORT, () => console.log( // eslint-disable-line no-console
`Websocket Server is now running on http://localhost:${WS_PORT}`
));
const subscriptionManager = new SubscriptionManager({
schema: executableSchema,
pubsub: pubsub,
setupFunctions: { /* your subscription channels */ },
});
subscriptionServer = new SubscriptionServer({
subscriptionManager: subscriptionManager
}, {
server: websocketServer,
path: '/',
});
...

您需要某种发布订阅服务,我们使用pubSub
。它包含在服务器文件中,如下所示:
import {
PubSub
} from 'graphql-subscriptions';
const pubsub = new PubSub();
export {
pubsub
};

答案 1 :(得分:0)
您可以创建一些实现start
方法的Web套接字服务器包装器,该方法将负责创建和运行WSServer
,并且它将使用{创建SubscriptionServer
{1}}
SubscriptionManager
创建// in subscription.js
import { PubSub, SubscriptionManager } from 'graphql-subscriptions';
const pubSub = new PubSub();
let subscriptionManagerOptions = {
schema: schema, // this is your graphql schema
setupFunctions: {
// here come your setup functions
},
pubSub: pubSub
};
const subscriptionManager = new SubscriptionManager(subscriptionManagerOptions);
export { pubSub, subscriptionManager };
后,我们现在可以实施subscriptionManager
WSServer
现在您可以在import { createServer } from 'http';
import { SubscriptionServer } from 'subscription-transport-ws';
import { subscriptionManager } from './subscription';
const webSocketServerWrapper = {
start: function(port){
const webSocketServer = createServer((request, response) => {
response.writeHead(404);
response.end();
});
webSocketServer.listen(port, () => {
console.log('WSServer listening on port ' + port);
});
new SubscriptionServer({
subscriptionManager,
onSubscribe: (message, options, request) => {
return Promise.resolve(Object.assign({}, options, {}));
}
}, webSocketServer);
}
};
export default webSocketServerWrapper;
等初始化文件中导入webSocketServerWrapper
,然后只需运行index.js
Here,我写的第二个答案,你可以找到一个负责创建示例订阅的代码以及如何处理它。