diff --git a/app/client-ecs.js b/app/client-ecs.js index 49a45d4..2e4c589 100644 --- a/app/client-ecs.js +++ b/app/client-ecs.js @@ -25,8 +25,21 @@ export default class ClientEcs extends Ecs { return cache.get(uri); } async readJson(uri) { - const chars = await this.readAsset(uri); - return chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {}; + const key = ['$$json', uri].join(':'); + if (!cache.has(key)) { + let promise, resolve, reject; + promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + cache.set(key, promise); + this.readAsset(uri) + .then((chars) => { + resolve(chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {}); + }) + .catch(reject); + } + return cache.get(key); } async readScript(uri, context = {}) { const code = await this.readAsset(uri); diff --git a/app/engine.js b/app/engine.js index fff04bc..390ac61 100644 --- a/app/engine.js +++ b/app/engine.js @@ -11,6 +11,12 @@ import createHomestead from './create-homestead.js'; import createHouse from './create-house.js'; import createPlayer from './create-player.js'; +import {LRUCache} from 'lru-cache'; + +const cache = new LRUCache({ + max: 128, +}); + export default class Engine { connectedPlayers = new Map(); @@ -38,11 +44,35 @@ export default class Engine { return engine.frame; } async readAsset(uri) { - return server.readAsset(uri); + if (!cache.has(uri)) { + let promise, resolve, reject; + promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + cache.set(uri, promise); + server.readAsset(uri) + .then(resolve) + .catch(reject); + } + return cache.get(uri); } async readJson(uri) { - const chars = await this.readAsset(uri); - return chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {}; + const key = ['$$json', uri].join(':'); + if (!cache.has(key)) { + let promise, resolve, reject; + promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + cache.set(key, promise); + this.readAsset(uri) + .then((chars) => { + resolve(chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {}); + }) + .catch(reject); + } + return cache.get(key); } async readScript(uri, context) { if (!uri) {