1
0

socket.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { ApiPromise, WsProvider } from '@polkadot/api'
  2. import { Api, Header, Status } from './types'
  3. import { types } from '@joystream/types'
  4. import chalk from 'chalk'
  5. import { Block } from './db/models'
  6. import { addBlock } from './joystream'
  7. export 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. }