1
0

socket.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. // TODO allow alternative backends
  8. const wsLocation = 'ws://localhost:9944'
  9. // 'wss://rome-rpc-endpoint.joystream.org:9944'
  10. module.exports = (io: any) => {
  11. const handleUpstream = async (api: Api) => {
  12. let status: Status = {}
  13. let lastHeader: Header
  14. api.derive.chain.subscribeNewHeads(async (header: Header) => {
  15. if (lastHeader && lastHeader.number === header.number)
  16. return console.debug(`skipping seen block`)
  17. lastHeader = header
  18. status = await addBlock(api, io, header, status)
  19. })
  20. }
  21. io.on('connection', async (socket: any) => {
  22. console.log(chalk.green(`[socket.io] Connection: ${socket.id}`))
  23. socket.on('get blocks', async (limit: number) => {
  24. const blocks = await Block.findAll({ limit, order: [['id', 'DESC']] })
  25. socket.emit('blocks', blocks)
  26. })
  27. socket.on('disconnect', async () => {
  28. console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`))
  29. })
  30. })
  31. const connectUpstream = async () => {
  32. try {
  33. console.debug(`[Joystream] Connecting to ${wsLocation}`)
  34. const provider = new WsProvider(wsLocation)
  35. const api = await ApiPromise.create({ provider, types })
  36. await api.isReady
  37. console.debug(`[Joystream] Connected.`)
  38. handleUpstream(api)
  39. } catch (e) {
  40. //console.log(`[Joystream] upstream connection failed`, e)
  41. }
  42. }
  43. connectUpstream()
  44. }