cubbot/src/utils/Data.ts

71 lines
1.9 KiB
TypeScript

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 }>
}
/** Load game data */
export default class Data {
private _ready = false
public get ready() {
return this._ready
}
private _entities?: { [name: string]: IEntityData }
public get entities() {
return this._entities
}
constructor(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.load(path), 500)
})
}).on('error', error => console.error({ msg: 'Downloading error', error }))
} else {
this.load(path)
}
}
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]
}
}
}
}
private load(path: string) {
try {
const data = JSON.parse(readFileSync(path).toString())[0] // NOTE: memory ???
this._entities = data.entities.entity
this._ready = true
} catch (error) {
console.error('/!\\ =( Please remove ' + path, error)
process.exit(1)
}
}
}