socket.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  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
  10. api.derive.chain.subscribeNewHeads(async (header: Header) => {
  11. if (lastHeader && lastHeader.number === header.number)
  12. return console.debug(`skipping seen block`)
  13. lastHeader = header
  14. status = await addBlock(api, io, header, status)
  15. })
  16. io.on('connection', async (socket: any) => {
  17. console.log(chalk.green(`[socket.io] Connection: ${socket.id}`))
  18. socket.on('get blocks', async (limit: number) => {
  19. const blocks = await Block.findAll({ limit, order: [['id', 'DESC']] })
  20. socket.emit('blocks', blocks)
  21. })
  22. socket.on('disconnect', async () => {
  23. console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`))
  24. })
  25. })
  26. }
  27. module.exports = { setupSocket }