socket.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const { Block } = require('./db/models')
  2. const chalk = require('chalk')
  3. const { types } = require('@joystream/types')
  4. const { ApiPromise, WsProvider } = require('@polkadot/api')
  5. const wsLocation = 'wss://rome-rpc-endpoint.joystream.org:9944'
  6. module.exports = (io) => {
  7. const initializeSocket = async () => {
  8. console.debug(`[Joystream] Connecting to ${wsLocation}`)
  9. const provider = new WsProvider(wsLocation)
  10. const api = await ApiPromise.create({ provider, types })
  11. await api.isReady
  12. console.debug(`[Joystream] Connected.`)
  13. api.derive.chain.subscribeNewHeads(async (header) => {
  14. const id = Number(header.number)
  15. const exists = await Block.findByPk(id)
  16. if (exists) return
  17. const timestamp = (await api.query.timestamp.now()).toNumber()
  18. const last = await Block.findByPk(id - 1)
  19. const blocktime = last ? timestamp - last.timestamp : 6000
  20. const block = await Block.create({
  21. id,
  22. timestamp,
  23. blocktime,
  24. author: header.author?.toString(),
  25. })
  26. console.log('[Joystream] block', block.id, block.blocktime, block.author)
  27. io.emit('block', block)
  28. })
  29. }
  30. io.on('connection', (socket) => {
  31. socket.emit('welcome', 'Websockets are awesome!')
  32. console.log(chalk.green(`[socket.io] Connection: ${socket.id}`))
  33. socket.on('disconnect', async () => {
  34. console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`))
  35. })
  36. })
  37. initializeSocket()
  38. }