我使用以下模式为Apollo / GraphQL订阅设置websockets连接:
import express from 'express';
import {
graphqlExpress,
graphiqlExpress,
} from 'apollo-server-express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { schema } from './src/schema';
const PORT = 3000;
const server = express();
server.use('*', cors({ origin: `http://localhost:${PORT}` }));
server.use('/graphql', bodyParser.json(), graphqlExpress({
schema
}));
server.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`
}));
// Wrap the Express server
const ws = createServer(server);
ws.listen(PORT, () => {
console.log(`Apollo 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',
});
});
如何更改连接以使用安全的websockets协议?简单地将'ws://'更改为'wss://'不起作用。
我为graphql-subscription
websocket安全连接做了一个样本。
关键是你需要tls
或ssl
凭证。
对于开发,您可以使用openssl
生成自签名凭据。
您需要使用https
而不是http
包。您还需要有证书。收集自签名或来自证书颁发机构。
它可能看起来像这样:
import { createServer } from 'https';
...
// load / get certificate
...
const wss = createServer(sslCredentails, server);
wss.listen(PORT, () => {
console.log(`Apollo Server is now running on https://localhost:${PORT}`);
// Set up the WebSocket for handling GraphQL subscriptions
new SubscriptionServer({
execute,
subscribe,
schema
}, {
server: wss,
path: '/subscriptions',
});
});