-
-
Save wbobeirne/e3575cd60ce7ac67680425bf02e9c0b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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