avocado-old/packages/resource/index.js

87 lines
1.6 KiB
JavaScript

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 this.loadCache[uri].then((json) => {
return JSON.parse(JSON.stringify(json));
});
}
if ('undefined' !== typeof window) {
return this.loadCache[uri] = fetch(uri).then((response) => {
return response.json();
}).then((json) => {
return json;
});
}
else {
return this.loadCache[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() {
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,
};
}
}