Skip to content

Instantly share code, notes, and snippets.

@feuGeneA
Last active June 24, 2020 16:25
Show Gist options
  • Save feuGeneA/da5c036dc92b42c1c55dc0522b4c3d81 to your computer and use it in GitHub Desktop.
Save feuGeneA/da5c036dc92b42c1c55dc0522b4c3d81 to your computer and use it in GitHub Desktop.
import createSubscriber from 'pg-listen';
// Function to sleep in between latency samples.
async function sleep(): Promise<void> {
const delay: number = 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
const subscriber = createSubscriber({ connectionString: 'http://postgres:password@localhost:5432' });
subscriber.notifications.on('my-channel', payload => {
console.log(`Received ${JSON.stringify(payload)}. Latency was ${Date.now() - payload.timestamp} ms`);
});
subscriber.events.on('error', error => {
console.error(`Fatal database connection error: ${error}`);
process.exit(1);
});
process.on('exit', () => { subscriber.close(); });
(async (): Promise<void> => {
await subscriber.connect();
await subscriber.listenTo('my-channel');
while (true) {
await subscriber.notify('my-channel', { timestamp: Date.now() });
await sleep();
}
})().catch(e => console.log(e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment