阿波罗联邦订阅是Apollo GraphQL的一种特殊订阅方式,可以用于实现实时数据的订阅和推送。下面是一个在Node.js 8.11.1上实现阿波罗联邦订阅的示例代码:
npm install apollo-server graphql graphql-subscriptions subscriptions-transport-ws
const { ApolloServer, gql } = require("apollo-server");
const { PubSub } = require("graphql-subscriptions");
const { execute, subscribe } = require("graphql");
const { createServer } = require("http");
const { SubscriptionServer } = require("subscriptions-transport-ws");
// 定义GraphQL类型和Resolvers
const typeDefs = gql`
type Query {
hello: String
}
type Mutation {
publishMessage(message: String!): String
}
type Subscription {
messagePublished: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello, world!"
},
Mutation: {
publishMessage: (_, { message }, { pubsub }) => {
pubsub.publish("MESSAGE_PUBLISHED", { messagePublished: message });
return message;
}
},
Subscription: {
messagePublished: {
subscribe: (_, __, { pubsub }) => pubsub.asyncIterator("MESSAGE_PUBLISHED")
}
}
};
// 创建PubSub实例
const pubsub = new PubSub();
// 创建Apollo Server
const server = new ApolloServer({
typeDefs,
resolvers,
context: { pubsub }
});
// 创建HTTP服务器
const httpServer = createServer();
server.applyMiddleware({ app: httpServer });
// 启动HTTP服务器
httpServer.listen({ port: 4000 }, () => {
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
});
// 创建Subscription服务器
const subscriptionServer = SubscriptionServer.create(
{
schema: server.schema,
execute,
subscribe
},
{
server: httpServer,
path: server.graphqlPath
}
);
console.log(`Subscription server ready at ws://localhost:4000${server.graphqlPath}`);
node server.js
现在,你可以使用GraphQL客户端来订阅messagePublished
事件并接收实时推送的消息。例如,使用Apollo Client进行订阅:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
import { WebSocketLink } from "@apollo/client/link/ws";
const client = new ApolloClient({
link: new WebSocketLink({
uri: "ws://localhost:4000/graphql",
options: {
reconnect: true
}
}),
cache: new InMemoryCache()
});
const subscription = client.subscribe({
query: gql`
subscription {
messagePublished
}
`
});
subscription.subscribe({
next: ({ data }) => console.log("Received new message:", data.messagePublished)
});
这样,当你在Mutation中发布一条消息时,订阅会立即收到推送的消息。