我使用的是带有react native和Relay的ExpressGraphql服务器。我的设备确实连接到订阅,但它没有订阅。这是我在服务器上的index.js
const subscriptionServer = SubscriptionServer.create(
{
execute,
subscribe,
schema,
onOperation: (message, params, webSocket) => {
console.log(params)
return params;
},
onConnect: () => {
// My device does connects
console.log("client connected")
}
},
{
server,
path: '/subscriptions'
},
);
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}));
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: `ws://127.0.0.1:8080/subscriptions`
}));
server.listen(PORT, ()=> {
console.log("Groceries running on port " + PORT)
console.log(
`subscriptions is now running on ws://localhost:${PORT}/subscriptions'}`
);
});
服务器上订阅的解析程序,很难弄清楚,因为每个人都在使用apolloGraphql中的可执行模式。
export default {
type: OrderEdges,
args: {
ShopId: {type: GraphQLID},
},
subscribe: withFilter(() => pubsub.asyncIterator('orderConfirmed'), (payload, variables) => {
console.log(payload)
console.log(variables)
return payload.orderConfirmed.node.ShopId == variables.ShopId;
}),
}
现在是react本机客户端。我的订阅设置与中继环境。
const setupSubscriptions = (config, variables, cacheConfig, observer) => {
const query = config.text; //does console logs the query
const subscriptionClient = new SubscriptionClient(`ws://192.168.0.100:8080/subscriptions`, {reconnect:true});
subscriptionClient.request({query, variables}, (err, result) => {
console.log(err) // doesn't get call inside the request method
observer.onNext(data:result)
})
}
我的订阅方式,
export default function() {
const variables = {
ShopId: shop.getShop()[0].id
}
requestSubscription(
environment,
{
subscription,
variables,
onCompleted: (res, err) => {
console.log(res)
console.log(err)
},
updater: (store) => {...},
onError: error => console.error(error),
onNext: (response) => {console.log(response)}
});
}
我打电话订阅的组件,
import subscription from '../../GraphQLQueries/subscriptions/orderConfirmed';
class OrdersBox extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
//initializing subscription
orderSubscriptions();
}
当设备启动应用程序时,我的设备已连接到web套接字,因为我可以在SubscriptionServer中的onConnect方法中看到console.log语句。但是,当有效载荷在突变后发布时,不会调用subscribe方法。我似乎不明白自己做错了什么。也许我缺少的是一些特定于反应的本地配置,因为当我在graphicql上测试它时,一切似乎都很好。我找不到任何与express graphql一起使用的react原生订阅和中继订阅的示例。
注意:当我使用graphicql订阅时,一切都正常。但不与反应本土和接力。
提前感谢各位……
我没有返回subscriptionClient.request方法。添加return语句解决了问题。在中使用subscribe方法时不必返回subscriptions-transport-ws@0.8.3.但是0.9.1版本用请求替换了subscribe函数,请求确实需要它返回。
try:
function setupSubscription(config, variables, cacheConfig, observer) {
const query = config.text;
const subscriptionClient = new SubscriptionClient(websocketURL, {
reconnect: true
});
const client = subscriptionClient.request({ query, variables }).subscribe({
next: result => {
observer.onNext({ data: result.data });
},
complete: () => {
observer.onCompleted();
},
error: error => {
observer.onError(error);
}
});
return {
dispose: client.unsubscribe
};
}
subscriptions-transport-ws@0.9.1