import * as ServiceSpec from "../spec/service" import * as fs from "fs-extra" import * as pathModule from "path" export class PersistentService extends ServiceSpec.PersistentService { storageName = "persistent.json" storagePath = pathModule.join(this.settings.persistent.storage, this.storageName) initialize() { this.services.GracefulShutdownService.graceful({ name: "persistent", timeout: 1000 * 30 }, (done) => { this.save() console.log("Persisted") done() }) this.storageName = this.settings.persistent.storageName || this.storageName this.storagePath = pathModule.join(this.settings.persistent.storage, this.storageName) fs.mkdirpSync(this.settings.persistent.storage) if (!fs.existsSync(this.storagePath)) { return } try { this.datas = JSON.parse(fs.readFileSync(this.storagePath, "utf8")) } catch (e) { console.error("Fail to load broken persistent files") return } } datas: { [key: string]: any } = {} tracks: { [name: string]: Type.Root.PersistentService.Persistentable } = {} track(obj: Type.Root.PersistentService.Persistentable) { if (this.tracks[obj.name]) { console.error(`Can't duplicate tracking ${obj.name}`) return false } this.tracks[obj.name] = obj } restore(obj: Type.Root.PersistentService.Persistentable) { let data = this.datas[obj.name] if (!data) { console.log("No restore for", obj.name) return false } obj.fromJSON(data) } save() { for (let name in this.tracks) { let obj = this.tracks[name] this.datas[name] = obj.toJSON() } fs.writeFileSync(this.storagePath, JSON.stringify(this.datas)) } }