import { ApiPromise, WsProvider } from '@polkadot/api' import { HeaderExtended } from '@polkadot/api-derive/types' import { Status } from './types' import chalk from 'chalk' import { Block } from './db/models' import { addBlock } from './joystream' export const setupSocket = async (io: any, api: ApiPromise) => { let status: Status, lastHeader: HeaderExtended api.derive.chain.subscribeNewHeads(async (header: HeaderExtended) => { if (header.number.toNumber() === lastHeader?.number.toNumber()) return if (!header.author) return 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}`)) ) }) }