import uuid from 'uuid/v4'; export class Resource { static load(uri) { return this.read(uri).then((json) => { const instance = new this(); return instance.fromJSON(json); }); } static read(uri) { if (!this.loadCache) { this.loadCache = {}; } if (this.loadCache[uri]) { return Promise.resolve(JSON.parse(JSON.stringify(this.loadCache[uri]))); } if ('undefined' !== typeof window) { return fetch(uri).then((response) => { return response.json(); }).then((json) => { return this.loadCache[uri] = json; }); } else { return new Promise((resolve, reject) => { const fs = require('fs'); const path = require('path'); const resourcePath = path.resolve(process.cwd(), 'resource'); fs.readFile(`${resourcePath}${uri}`, (error, buffer) => { if (error) { return reject(error); } resolve(this.loadCache[uri] = JSON.parse(buffer.toString('utf8'))); }); }); } } constructor() { this._uri = undefined; this._uuid = undefined; this._instanceUuid = uuid(); } fromJSON({uri, uuid}) { this._uri = uri; this._uuid = uuid; return this; } get instanceUuid() { return this._instanceUuid; } regenerateUuid() { this._uuid = uuid(); } get uuid() { return this._uuid; } set uuid(uuid) { this._uuid = uuid; } get uri() { return this._uri; } set uri(uri) { this._uri = uri; } toJSON() { return { uuid: this._uuid, uri: this._uri, }; } }