socket.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { Api, Header, Status } from './types'
  2. const { types } = require('@joystream/types')
  3. const { Block } = require('./db/models')
  4. const { ApiPromise, WsProvider } = require('@polkadot/api')
  5. const { addBlock } = require('./joystream')
  6. const chalk = require('chalk')
  7. const setupSocket = async (io: any, api: Api) => {
  8. let status: Status
  9. let lastHeader: Header = { number: 0, timestamp: 0, author: '' }
  10. api.derive.chain.subscribeNewHeads(async (header: Header) => {
  11. const id = +header.number
  12. if (id === +lastHeader.number)
  13. return console.debug(
  14. `[Joystream] Skipping duplicate block ${id} (TODO handleFork)`
  15. )
  16. lastHeader = header
  17. status = await addBlock(api, io, header, status)
  18. })
  19. io.on('connection', async (socket: any) => {
  20. console.log(chalk.green(`[socket.io] Connection: ${socket.id}`))
  21. socket.on('get blocks', async (limit: number) => {
  22. const blocks = await Block.findWithIncludes({
  23. limit,
  24. order: [['id', 'DESC']],
  25. })
  26. socket.emit('blocks', blocks)
  27. })
  28. socket.on('disconnect', async () => {
  29. console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`))
  30. })
  31. })
  32. }
  33. module.exports = { setupSocket }