2019-03-17 23:45:48 -05:00
|
|
|
import uuid from 'uuid/v4';
|
|
|
|
|
|
|
|
export class Resource {
|
|
|
|
|
2019-03-19 18:05:12 -05:00
|
|
|
static load(uri) {
|
|
|
|
return this.read(uri).then((json) => {
|
|
|
|
const instance = new this();
|
|
|
|
return instance.fromJSON(json);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
static read(uri) {
|
2019-03-20 18:26:55 -05:00
|
|
|
if (!this.loadCache) {
|
|
|
|
this.loadCache = {};
|
|
|
|
}
|
|
|
|
if (this.loadCache[uri]) {
|
|
|
|
return Promise.resolve(JSON.parse(JSON.stringify(this.loadCache[uri])));
|
|
|
|
}
|
2019-03-19 18:05:12 -05:00
|
|
|
if ('undefined' !== typeof window) {
|
|
|
|
return fetch(uri).then((response) => {
|
|
|
|
return response.json();
|
2019-03-20 18:26:55 -05:00
|
|
|
}).then((json) => {
|
|
|
|
return this.loadCache[uri] = json;
|
2019-03-19 18:05:12 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
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);
|
|
|
|
}
|
2019-03-20 18:26:55 -05:00
|
|
|
resolve(this.loadCache[uri] = JSON.parse(buffer.toString('utf8')));
|
2019-03-19 18:05:12 -05:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-17 23:45:48 -05:00
|
|
|
constructor() {
|
|
|
|
this.uri_PRIVATE = undefined;
|
|
|
|
this.uuid_PRIVATE = undefined;
|
|
|
|
this.instanceUuid_PRIVATE = uuid();
|
|
|
|
}
|
|
|
|
|
|
|
|
fromJSON({uri, uuid}) {
|
|
|
|
this.uri_PRIVATE = uri;
|
|
|
|
this.uuid_PRIVATE = uuid;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
get instanceUuid() {
|
|
|
|
return this.instanceUuid_PRIVATE;
|
|
|
|
}
|
|
|
|
|
|
|
|
regenerateUuid() {
|
|
|
|
this.uuid_PRIVATE = uuid();
|
|
|
|
}
|
|
|
|
|
|
|
|
get uuid() {
|
|
|
|
return this.uuid_PRIVATE;
|
|
|
|
}
|
|
|
|
|
|
|
|
set uuid(uuid) {
|
|
|
|
this.uuid_PRIVATE = uuid;
|
|
|
|
}
|
|
|
|
|
|
|
|
get uri() {
|
|
|
|
return this.uri_PRIVATE;
|
|
|
|
}
|
|
|
|
|
|
|
|
set uri(uri) {
|
|
|
|
this.uri_PRIVATE = uri;
|
|
|
|
}
|
|
|
|
|
|
|
|
toJSON() {
|
|
|
|
return {
|
|
|
|
uuid: this.uuid_PRIVATE,
|
|
|
|
uri: this.uri_PRIVATE,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|