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 = { 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}`)) }) }) } module.exports = { setupSocket }