Skip to content

Instantly share code, notes, and snippets.

@wbobeirne
Last active June 7, 2019 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wbobeirne/e3575cd60ce7ac67680425bf02e9c0b4 to your computer and use it in GitHub Desktop.
Save wbobeirne/e3575cd60ce7ac67680425bf02e9c0b4 to your computer and use it in GitHub Desktop.
// API Routes
app.ws('/api/posts', (ws) => {
// Send all the posts we have initially
postsManager.getPaidPosts().forEach(post => {
ws.send(JSON.stringify({
type: 'post',
data: post,
}));
});
// Send each new post as it's paid for. If we error out, just close
// the connection and stop listening.
const postListener = (post: any) => {
ws.send(JSON.stringify({
type: 'post',
data: post,
}));
};
postsManager.addListener('post', postListener);
// Keep-alive by pinging every 10s
const pingInterval = setInterval(() => {
ws.send(JSON.stringify({ type: 'ping' }));
}, 10000);
// Stop listening if they close the connection
ws.addEventListener('close', () => {
postsManager.removeListener('post', postListener);
clearInterval(pingInterval);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment