avocado-old/packages/resource/index.js

87 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
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) {
2019-03-20 18:26:55 -05:00
if (!this.loadCache) {
this.loadCache = {};
}
if (this.loadCache[uri]) {
return this.loadCache[uri].then((json) => {
return JSON.parse(JSON.stringify(json));
});
2019-03-20 18:26:55 -05:00
}
if ('undefined' !== typeof window) {
return this.loadCache[uri] = fetch(uri).then((response) => {
return response.json();
2019-03-20 18:26:55 -05:00
}).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')));
});
});
}
}
2019-03-17 23:45:48 -05:00
constructor() {
2019-04-07 12:00:11 -05:00
this._uri = undefined;
this._uuid = undefined;
this._instanceUuid = uuid();
2019-03-17 23:45:48 -05:00
}
fromJSON({uri, uuid}) {
2019-04-07 12:00:11 -05:00
this._uri = uri;
this._uuid = uuid;
2019-03-17 23:45:48 -05:00
return this;
}
get instanceUuid() {
2019-04-07 12:00:11 -05:00
return this._instanceUuid;
2019-03-17 23:45:48 -05:00
}
regenerateUuid() {
2019-04-07 12:00:11 -05:00
this._uuid = uuid();
2019-03-17 23:45:48 -05:00
}
get uuid() {
2019-04-07 12:00:11 -05:00
return this._uuid;
2019-03-17 23:45:48 -05:00
}
set uuid(uuid) {
2019-04-07 12:00:11 -05:00
this._uuid = uuid;
2019-03-17 23:45:48 -05:00
}
get uri() {
2019-04-07 12:00:11 -05:00
return this._uri;
2019-03-17 23:45:48 -05:00
}
set uri(uri) {
2019-04-07 12:00:11 -05:00
this._uri = uri;
2019-03-17 23:45:48 -05:00
}
toJSON() {
return {
2019-04-07 12:00:11 -05:00
uuid: this._uuid,
uri: this._uri,
2019-03-17 23:45:48 -05:00
};
}
}