import fs, { readFileSync } from 'fs' import https from 'https' import { Logger } from 'pino' export interface IEntityData { id: number name: string display_name: string height: number width: number metadata: Array<{ entity?: string }> } export interface IItemData { display_name: string max_stack_size: number numeric_id: number } /** Load game data */ export default class Data { private _onReady: Array<(data: Data) => void> = [] private _entities?: { [name: string]: IEntityData } public get entities() { return this._entities } private _items?: { [name: string]: IItemData } public get items() { return this._items } public onReady(cb: ((data: Data) => void)) { this._onReady.push(cb) } public getEntityById(entityId: number) { if (this._entities) { for (const name in (this._entities as object)) { if (this._entities[name].id === entityId) { return this._entities[name] } } } } public load(source: string, directory: string, version: string, logger: Logger) { logger.debug('Loading data file') const path = directory + version + '.json' if (!fs.existsSync(directory)) { fs.mkdirSync(directory) } if (!fs.existsSync(path)) { logger.warn({ msg: 'Data file must be downloaded', type: 'version', value: version, note: 'will probably fail' }) const url = source + version + '.json' const out = fs.createWriteStream(path) https.get(url, res => { res.on('data', data => out.write(data)) res.on('error', error => console.error({ msg: 'Downloading error', error })) res.on('end', () => { out.close() setTimeout(() => this.read(path), 500) }) }).on('error', error => console.error({ msg: 'Downloading error', error })) } else { this.read(path) } } private read(path: string) { try { const data = JSON.parse(readFileSync(path).toString())[0] // NOTE: memory ??? this._entities = data.entities.entity this._items = data.items.item this._onReady.forEach(cb => cb(this)) } catch (error) { console.error('/!\\ =( Please remove ' + path, error) process.exit(1) } } }