apolloserver subscription
Subscriptions 是一种操作用于监视服务器端的事件。apollo server在不需要新增配置的情况下就支持Graphql的subscriptions操作。其他集成的服务器也支持subscriptions操作如apollo-server-express、apollo-server-hapi等。
Subscriptions Example
订阅操作依赖publish(发布)和subscribe(订阅)来生成事件通知订阅者。PubSub是一个工厂,可以创建事件生成器,用于所有支持的包。Pubsub是PubSubEngine实现的接口,可以广泛的用于服务器端事件的生成。
const { PubSub } = require('apollo-server');
const pubsub = new PubSub();
subscription和query和mutation一样也是一个根类型。我们需要在schema中定义subscription
const typeDefs = gql`
type Subscription {
postAdded: Post
}
type Query {
posts: [Post]
}
type Mutation {
addPost(author: String, comment: String): Post
}
type Post {
author: String
comment: String
}
`
在解析器函数中,我们使用一个异步事件遍历器来监听事件的发生。在mutation中使用publish来通知事件已发生。
const POST_ADDED = 'POST_ADDED';
const resolvers = {
Subscription: {
postAdded: {
// Additional event labels can be passed to asyncIterator creation
subscribe: () => pubsub.asyncIterator([POST_ADDED]),
},
},
Query: {
posts(root: any, args: any, context: any) {
return postController.posts();
},
},
Mutation: {
addPost(root: any, args: any, context: any) {
pubsub.publish(POST_ADDED, { postAdded: args });
return postController.addPost(args);
},
},
};
publish也可以在解析器之外调用。
Context with Subscriptions
为订阅创建上下文。
const server = new ApolloServer({
schema,
context: async ({ req, connection }) => {
if (connection) {
// check connection for metadata
return {};
} else {
// check from req
const token = req.headers.authorization || "";
return { token };
}
},
});
Authentication Over WebSocket
浙公网安备 33010602011771号