import { Api, Header, Status } from './types' const { types } = require('@joystream/types') const { Block } = require('./db/models') const { ApiPromise, WsProvider } = require('@polkadot/api') const { addBlock } = require('./joystream') const chalk = require('chalk') const setupSocket = async (io: any, api: Api) => { let status: Status = {} let lastHeader: Header api.derive.chain.subscribeNewHeads(async (header: Header) => { if (lastHeader && lastHeader.number === header.number) return console.debug(`skipping seen block`) 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.findAll({ limit, order: [['id', 'DESC']] }) socket.emit('blocks', blocks) }) socket.on('disconnect', async () => { console.log(chalk.red(`[socket.io] Disconnect: ${socket.id}`)) }) }) } module.exports = { setupSocket }