import { ApiPromise, WsProvider } from '@polkadot/api' import { Api, Header, Status } from './types' import { types } from '@joystream/types' import chalk from 'chalk' import { Block } from './db/models' import { addBlock } from './joystream' export const setupSocket = async (io: any, api: Api) => { let status: Status let lastHeader: Header = { number: 0, timestamp: 0, author: '' } api.derive.chain.subscribeNewHeads(async (header: Header) => { const id = +header.number if (id === +lastHeader.number) return console.debug( `[Joystream] Skipping duplicate block ${id} (TODO handleFork)` ) lastHeader = header status = await addBlock(api, io, header, status) }) io.on('connection', async (socket: any) => { console.log(chalk.green(`[socket.io] Connection: ${socket.id}`)) socket.on('get blocks', async (limit: number) => { const blocks = await Block.findWithIncludes({ limit, order: [['id', 'DESC']], }) socket.emit('blocks', blocks) }) socket.on('disconnect', async () => { console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`)) }) }) }