forked from casper-ecosystem/lottery-demo-dapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent-handler.ts
83 lines (67 loc) · 2.36 KB
/
event-handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import 'reflect-metadata';
import { config } from './config';
import WebSocket from 'ws';
import { Play } from './entity/play.entity';
import { PlayRepository } from './repository/play';
import { PlayEventPayload, Event } from './events';
import { AppDataSource } from './data-source';
async function main() {
await AppDataSource.initialize();
const playsRepository = new PlayRepository(AppDataSource);
const ws = new WebSocket(
`${config.csprCloudStreamingUrl}/contract-events?contract_package_hash=${config.lotteryContractPackageHash}`,
{
headers: {
authorization: config.csprCloudAccessKey,
},
},
);
ws.on('open', () => {
console.log(`Connected to streaming API: ${config.csprCloudStreamingUrl}`);
})
let lastPingTimestamp = new Date();
setInterval(() => {
const now = new Date();
if (now.getTime() - lastPingTimestamp.getTime() > config.pingCheckIntervalInMilliseconds) {
console.log(`No ping events from Streaming API for ${config.pingCheckIntervalInMilliseconds/1000} seconds, closing ws connection...`);
ws.close();
process.exit(1);
}
}, config.pingCheckIntervalInMilliseconds);
ws.on('message', async (data: Buffer) => {
const rawData = data.toString();
if (rawData === 'Ping') {
lastPingTimestamp = new Date();
return;
}
try {
console.log('New event: ', rawData);
const event = JSON.parse(rawData) as Event<PlayEventPayload>;
const play: Partial<Play> = {
playId: event.data.data.play_id,
roundId: event.data.data.round_id.toString(),
playerAccountHash: event.data.data.player.replace(/^account-hash-/, ''),
prizeAmount: event.data.data.prize_amount,
jackpotAmount: event.data.data.jackpot_amount,
isJackpot: event.data.data.is_jackpot,
deployHash: event.extra.deploy_hash,
timestamp: new Date(event.data.data.timestamp),
};
await playsRepository.save(play);
} catch (err) {
console.log('Error parsing message:', err);
}
});
ws.on('error', (err) => {
console.log(`Received a WS error: ${err.message}`);
ws.close();
console.log('Disconnected from Streaming API');
process.exit(1);
})
ws.on('close', () => {
console.log('Disconnected from Streaming API');
process.exit(1);
});
console.log('Handler started running...')
}
main();