1
0

socket.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. const initStatus = {
  9. block: 0,
  10. era: 0,
  11. round: 0,
  12. members: 0,
  13. channels: 0,
  14. categories: 0,
  15. threads: 0,
  16. posts: 0,
  17. proposals: 0,
  18. proposalPosts: 0,
  19. }
  20. const number = (await api.derive.chain.bestNumber()).toNumber()
  21. let lastHeader: Header = { number, timestamp: 0, author: '' }
  22. let status: Status = await updateStatus(api, initStatus, lastHeader.number)
  23. api.derive.chain.subscribeNewHeads(async (header: Header) => {
  24. const id = +header.number
  25. if (id === +lastHeader.number)
  26. return console.debug(
  27. `[Joystream] Skipping duplicate block ${id} (TODO handleFork)`
  28. )
  29. lastHeader = header
  30. status = await addBlock(api, io, header, status)
  31. })
  32. io.on('connection', async (socket: any) => {
  33. console.log(chalk.green(`[socket.io] Connection: ${socket.id}`))
  34. socket.on('get blocks', async (limit: number) => {
  35. const blocks = await Block.findWithIncludes({
  36. limit,
  37. order: [['id', 'DESC']],
  38. })
  39. socket.emit('blocks', blocks)
  40. })
  41. socket.on('disconnect', async () => {
  42. console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`))
  43. })
  44. })
  45. }
  46. module.exports = { setupSocket }