socket.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. import { ApiPromise, WsProvider } from '@polkadot/api'
  2. import { HeaderExtended } from '@polkadot/api-derive/types'
  3. import { Status } from './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: ApiPromise) => {
  8. let status: Status, lastHeader: HeaderExtended
  9. api.derive.chain.subscribeNewHeads(async (header: HeaderExtended) => {
  10. if (header.number.toNumber() === lastHeader?.number.toNumber()) return
  11. if (!header.author) return
  12. lastHeader = header
  13. status = await addBlock(api, io, header, status)
  14. })
  15. io.on('connection', async (socket: any) => {
  16. console.log(chalk.green(`[socket.io] Connection: ${socket.id}`))
  17. socket.on('get blocks', async (limit: number) => {
  18. const blocks = await Block.findWithIncludes({
  19. limit,
  20. order: [['id', 'DESC']],
  21. })
  22. socket.emit('blocks', blocks)
  23. })
  24. socket.on('disconnect', async () =>
  25. console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`))
  26. )
  27. })
  28. }