import { Injectable , OnApplicationShutdown } from '@nestjs/common' ; import { hexToU8a } from '@polkadot/util' ; import { Sequelize } from 'sequelize' ; import { NodeConfig } from '../configure/NodeConfig' ; import { SubqueryProject } from '../configure/project.model' ; import { PoiFactory , PoiRepo , ProofOfIndex } from './entities/Poi.entity' ; const DEFAULT_PARENT_HASH = hexToU8a ( '0x00' ) ; @ Injectable ( ) export class PoiService implements OnApplicationShutdown { private isShutdown = false ; private latestPoiBlockHash : Uint8Array ; private poiRepo : PoiRepo ; private schema : string ; private latestPoiBlock : ProofOfIndex ; constructor ( protected nodeConfig , protected project , protected sequelize ) { } onApplicationShutdown ( ) { this . isShutdown = true ; } async init ( schema ) { this . schema = schema ; this . poiRepo = PoiFactory ( this . sequelize , this . schema ) ; this . latestPoiBlockHash = await this . getLatestPoiBlockHash ( ) ; } async fetchPoiBlockHashFromDb ( ) { const lastPoi = await this . poiRepo . findOne ( { order : [ [ 'id' , 'DESC' ] ] , } ) ; if ( lastPoi === null || lastPoi === undefined ) { return null ; } else if ( lastPoi !== null && lastPoi . hash ) { return lastPoi . hash ; } else { throw new Error ( `Poi found but can not get latest hash` ) ; } } async getLatestPoiBlockHash ( ) { if ( ! this . latestPoiBlockHash ) { const poiBlockHash = await this . fetchPoiBlockHashFromDb ( ) ; if ( poiBlockHash === null || poiBlockHash === undefined ) { this . latestPoiBlockHash = DEFAULT_PARENT_HASH ; } else { this . latestPoiBlockHash = poiBlockHash ; } } return this . latestPoiBlockHash ; } setLatestPoiBlockHash ( hash ) { this . latestPoiBlockHash = hash ; } }