avocado-old/packages/resource/index.js

85 lines
1.7 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 Promise.resolve(JSON.parse(JSON.stringify(this.loadCache[uri])));
}
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;
});
}
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-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,
};
}
}