avocado-old/packages/resource/resource.js

104 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-05-21 21:08:06 -05:00
import uuid from 'uuid/v4';
import {compose, merge, Property} from '@avocado/core';
const decorate = compose(
Property('instanceUuid'),
Property('uri'),
Property('uuid'),
)
export class Resource extends decorate(class {}) {
2019-09-16 19:02:02 -05:00
constructor() {
super();
this.instanceUuid = Resource.uuid();
}
fromJSON({uri, uuid}) {
if (uri) {
this.uri = uri;
}
if (uuid) {
this.uuid = uuid;
}
return this;
}
2019-05-21 21:08:06 -05:00
static load(uri) {
return this.read(uri).then((json) => {
2019-10-07 06:17:15 -05:00
return new this({
uri,
...json,
});
2019-05-21 21:08:06 -05:00
});
}
2019-09-16 19:04:02 -05:00
static loadOrInstance(json) {
if (json.uri) {
return this.read(json.uri).then((readJson) => {
return new this(readJson, json);
});
}
else {
return Promise.resolve(new this(json));
}
}
2019-05-21 21:08:06 -05:00
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) {
this.readCache[uri] = fetch(uri).then((response) => {
return response.json();
});
}
else {
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')));
});
});
}
// Allow "base" JSON.
return this.readCache[uri].then((json) => {
if ('undefined' !== typeof json.base) {
return this.read(json.base).then((baseJSON) => {
return merge({}, baseJSON, json);
});
}
return json;
2020-06-21 11:22:10 -05:00
}).catch((error) => {
console.error(`Failed loading '${uri}'.`);
2019-05-21 21:08:06 -05:00
});
}
regenerateUuid() {
this.uuid = Resource.uuid();
}
toJSON() {
return {
uuid: this.uuid,
uri: this.uri,
};
}
2019-09-16 19:02:02 -05:00
static uuid() {
return uuid();
}
2019-05-21 21:08:06 -05:00
}