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) => { const initStatus = { block: 0, era: 0, round: 0, members: 0, channels: 0, categories: 0, threads: 0, posts: 0, proposals: 0, proposalPosts: 0, } const number = (await api.derive.chain.bestNumber()).toNumber() let lastHeader: Header = { number, timestamp: 0, author: '' } let status: Status = await updateStatus(api, initStatus, lastHeader.number) 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 }