Skip to content

Instantly share code, notes, and snippets.

@mb8z
Last active August 10, 2023 12:05
Show Gist options
  • Save mb8z/8d320fc4dafc7c072bce1f926e75c63c to your computer and use it in GitHub Desktop.
Save mb8z/8d320fc4dafc7c072bce1f926e75c63c to your computer and use it in GitHub Desktop.
Healthie
const token = 'gb_sbox_....'; // Actual user's API key
const url = `wss://ws.staging.gethealthie.com/subscriptions?token=${token}`;
const sub = useGQLSubscription({ url });
const NOTE_ADDED_SUBSCRIPTION = `
subscription ($conversationId: String) {
noteAddedSubscription(conversationId: $conversationId) {
id
content
__typename
}
}
`;
sub.subscribe({
query: NOTE_ADDED_SUBSCRIPTION,
variables: { conversationId: '246395' }, // Hardcoded conversation ID for now
});
// Here are the logs we're seeing
{"sid": "ofS9C3ExV69uL15M1KgK5", "type": "welcome"}
{"identifier": "{\"channel\":\"GraphqlChannel\",\"channelId\":\"189db9bce8a\"}", "type": "confirm_subscription"}
{"message": 1691606492, "type": "ping"}
import React from 'react';
import useWebSocket from 'react-use-websocket';
import * as Types from './types';
const generateChannelId = () => Math.round(Date.now() + Math.random() * 100000).toString(16);
export const useGQLSubscription = (props: Types.Props) => {
const { url } = props;
const identifier = React.useMemo(() => JSON.stringify({
channel: 'GraphqlChannel',
channelId: generateChannelId(),
}), []);
const ws = useWebSocket(url!, {
onMessage: (event) => {
const data = JSON.parse(event.data);
if (data.type === 'confirm_subscription') {
console.log('Subscription confirmed!');
}
},
});
const subscribe = React.useCallback((data?: any) => {
ws.sendJsonMessage({
command: 'subscribe',
identifier,
});
// TODO: Remove this timeout
setTimeout(() => {
ws.sendJsonMessage({
command: 'message',
identifier,
data: JSON.stringify(data),
});
}, 2000);
}, []);
return {
isConnected: !!ws.lastMessage,
lastMessage: ws.lastJsonMessage,
subscribe,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment