import uuid from 'uuid/v4'; import {compose, Property} from '@avocado/core'; const decorate = compose( Property('instanceUuid'), Property('uri'), Property('uuid'), ) export class Resource extends decorate(class {}) { static load(uri) { return this.read(uri).then((json) => { const instance = new this(); return instance.fromJSON(json); }); } static read(uri) { if (!this.readCache) { this.readCache = {}; } if (this.readCache[uri]) { return this.readCache[uri].then((json) => { return JSON.parse(JSON.stringify(json)); }); } if ('undefined' !== typeof window) { return this.readCache[uri] = fetch(uri).then((response) => { return response.json(); }).then((json) => { return json; }); } else { return this.readCache[uri] = 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(JSON.parse(buffer.toString('utf8'))); }); }); } } constructor() { super(); this.instanceUuid = uuid(); } fromJSON({uri, uuid}) { if (uri) { this.uri = uri; } if (uuid) { this.uuid = uuid; } return this; } regenerateUuid() { this.uuid = uuid(); } toJSON() { return { uuid: this.uuid, uri: this.uri, }; } }