import { Coin, AccountMap, TransactionMap, SubscriptionResponse, ErrorResponse, SuccessResponse, parseResponse, parseSubResponse } from "frontblock-generic/Types"; import { FrontblockApi as FrontblockApi } from "frontblock-generic/Api"; import * as Logger from 'log4js' import { ConfigLoader } from "frontblock-generic/Plugin"; Logger.configure({ appenders: { "frontblock-api-client": { type: 'stdout' }, //app: { type: 'file', filename: 'application.log' } }, categories: { default: { appenders: [ 'frontblock-api-client' ], level: 'debug' } } }) const logger = Logger.getLogger("frontblock-api-client") const bsock = require('bsock') export type FrontblockApiConf = { apiHost:string apiPort:number tls?:boolean apiKey?:string } /** * Frontblock api connection lib */ export default class FrontblockApiClient extends ConfigLoader implements FrontblockApi{ protected started:boolean = false protected apikey:string = "" protected socket constructor(){ super("FrontblockApiClient") } getDefaultConfig(): FrontblockApiConf { return { apiHost: "api.testnet.frontblock.me", apiKey: "", apiPort: 10001, tls: false } } async consume(apikey: string, uid: string, callback: (tx: TransactionMap[C]) => void): Promise { const r = await this.socket.call("consume", apikey, uid) const res = parseSubResponse(r) if(res instanceof SubscriptionResponse){ this.socket.hook(res.uid, (tx) => { const deserialized = JSON.parse(tx) callback(deserialized) }) } return res } async quit(apikey: string, consumerUid: string): Promise { const r = await this.socket.call("quit", apikey, consumerUid) const res = parseResponse(r) return res } async subscribe(apikey: string, coin: C, account: AccountMap[C]): Promise { const r = await this.socket.call("subscribe", apikey, coin, account) const res = parseSubResponse(r) return res } async subsume(apikey: string, coin: C, account: AccountMap[C], callback: (tx: TransactionMap[C]) => void): Promise { const r = await this.socket.call("subsume", apikey, coin, account) const res = parseSubResponse(r) if(res instanceof SubscriptionResponse){ this.socket.hook(res.uid, (tx) => { const deserialized = JSON.parse(tx) callback(deserialized) }) } return res } async unsubscribe(apikey:string, uid: string): Promise { const r = await this.socket.call('unsubscribe', apikey, uid) const res = parseResponse(r) if(res instanceof SuccessResponse) this.socket.unhook(uid) return res } async getPluginList(): Promise { return await this.socket.call('getPluginList') } connect(): void { if(this.started){ logger.warn("FrontblockApiClient has already been started. Ignoring") return } logger.info("Starting apiClient with ", this.conf) this.socket = bsock.connect(this.conf.apiPort, this.conf.apiHost, this.conf.tls!=null?this.conf.tls:false) this.started = true } disconnect(): void { if(!this.started){ logger.warn("FrontblockApiClient has not been started. Ignoring") return } this.socket.close() } }