hasura graphql subscriptions 使用
subscriptions graphql 的一项实时数据推送的功能,还是很方便的,自己在直接使用subscriptions-transport-ws npm 包
的时候运行一直有错误(主要是依赖的apollo版本),还好hasura graphql 默认提供了一个开发模版,还是比较方便的
模版clone
git clone https://github.com/hasura/nodejs-graphql-subscriptions-boilerplate.git
基本代码集成
- 使用模版(graphql server是自己的)
const { execute } = require('apollo-link');
const { WebSocketLink } = require('apollo-link-ws');
const { SubscriptionClient } = require('subscriptions-transport-ws');
const ws = require('ws');
const getWsClient = function(wsurl) {
const client = new SubscriptionClient(
wsurl, {reconnect: true}, ws
);
return client;
};
// wsurl: GraphQL endpoint
// query: GraphQL query (use gql`` from the 'graphql-tag' library)
// variables: Query variables object
const createSubscriptionObservable = (wsurl, query, variables) => {
const link = new WebSocketLink(getWsClient(wsurl));
return execute(link, {query: query, variables: variables});
};
const gql = require('graphql-tag');
const SUBSCRIBE_QUERY = gql`
subscription {
apps {
dr
id
appname
}
}
`;
function main() {
const subscriptionClient = createSubscriptionObservable(
'http://myserver:port/v1alpha1/graphql', // GraphQL endpoint
SUBSCRIBE_QUERY, // Subscription query
);
var consumer = subscriptionClient.subscribe(eventData => {
console.log("Received event: ");
console.log(JSON.stringify(eventData, null, 2));
}, (err) => {
console.log('Err');
console.log(err);
});
}
main();
- 效果
说明
主要是package.json
- package.json
{
"name": "nodejs-graphql-subscriptions-boilerplate",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"start":"node index"
},
"author": "Karthik V",
"license": "ISC",
"dependencies": {
"apollo-link": "^1.2.2",
"apollo-link-ws": "^1.0.8",
"graphql": "^0.13.2",
"graphql-tag": "^2.9.2",
"subscriptions-transport-ws": "^0.9.12",
"ws": "^5.2.2" // 这个比较重要,一般可能会忘记添加,会有提示websocket 没有实现,还好官方模版提供好了
}
}
- 数据查询demo
subscription:
subscription appdemo($input:Int!) {
apps (where:{
id: {
_eq:$input
}}
)
{
dr
id
appname
}
}
查询参数:
const subscriptionClient = createSubscriptionObservable(
'http://server:port/v1alpha1/graphql', // GraphQL endpoint
SUBSCRIBE_QUERY, // Subscription query
{id:1}
);
参考资料
https://github.com/hasura/nodejs-graphql-subscriptions-boilerplate
https://www.apollographql.com/docs/react/advanced/subscriptions.html