使用Apollo GraphQL进行非Web套接字订阅的解决方法如下:
npm install apollo-client apollo-server
const { ApolloServer, gql, PubSub } = require('apollo-server');
// 创建一个PubSub实例
const pubsub = new PubSub();
// 定义GraphQL schema
const typeDefs = gql`
type Query {
hello: String
}
type Subscription {
message: String
}
`;
// 定义解析器
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
Subscription: {
message: {
subscribe: () => pubsub.asyncIterator(['MESSAGE']),
},
},
};
// 创建Apollo Server实例
const server = new ApolloServer({
typeDefs,
resolvers,
});
// 启动服务器
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
subscribe
方法来订阅服务器发送的更新。以下示例展示了如何在React中使用Apollo Client进行订阅:import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, useSubscription, gql } from '@apollo/client';
// 创建Apollo Client实例
const client = new ApolloClient({
uri: 'http://localhost:4000',
cache: new InMemoryCache(),
});
// 定义GraphQL订阅
const MESSAGE_SUBSCRIPTION = gql`
subscription {
message
}
`;
// 订阅组件
function MessageSubscription() {
const { data } = useSubscription(MESSAGE_SUBSCRIPTION);
if (data) {
return {data.message};
}
return null;
}
// 应用组件
function App() {
return (
);
}
export default App;
在上述例子中,客户端使用Apollo Client的useSubscription
hook来订阅服务器发送的message
更新。当服务器发送新的message
时,useSubscription
hook将会触发,并且可以通过data
属性访问到更新的数据。
这就是使用Apollo GraphQL进行非Web套接字订阅的基本解决方案。请根据你的具体需求进行修改和扩展。