avocado-old/packages/resource/index.js

84 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import uuid from 'uuid/v4';
2019-05-17 04:34:40 -05:00
import {compose, merge, Property} from '@avocado/core';
2019-04-28 08:29:01 -05:00
const decorate = compose(
Property('instanceUuid'),
Property('uri'),
Property('uuid'),
)
export class Resource extends decorate(class {}) {
2019-03-17 23:45:48 -05:00
static load(uri) {
return this.read(uri).then((json) => {
return new this(json);
});
}
static read(uri) {
2019-04-21 22:03:53 -05:00
if (!this.readCache) {
this.readCache = {};
2019-03-20 18:26:55 -05:00
}
2019-04-21 22:03:53 -05:00
if (this.readCache[uri]) {
return this.readCache[uri].then((json) => {
return JSON.parse(JSON.stringify(json));
});
2019-03-20 18:26:55 -05:00
}
if ('undefined' !== typeof window) {
2019-05-16 21:53:49 -05:00
this.readCache[uri] = fetch(uri).then((response) => {
return response.json();
});
}
else {
2019-05-16 21:53:49 -05:00
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')));
});
});
}
2019-05-16 21:53:49 -05:00
// Allow "base" JSON.
return this.readCache[uri].then((json) => {
if ('undefined' !== typeof json.base) {
return this.read(json.base).then((baseJSON) => {
2019-05-17 04:34:40 -05:00
return merge({}, baseJSON, json);
2019-05-16 21:53:49 -05:00
});
}
return json;
});
}
2019-03-17 23:45:48 -05:00
constructor() {
2019-04-28 08:29:01 -05:00
super();
this.instanceUuid = uuid();
2019-03-17 23:45:48 -05:00
}
fromJSON({uri, uuid}) {
2019-04-28 08:29:01 -05:00
if (uri) {
this.uri = uri;
}
if (uuid) {
this.uuid = uuid;
}
2019-03-17 23:45:48 -05:00
return this;
}
regenerateUuid() {
2019-04-28 08:29:01 -05:00
this.uuid = uuid();
2019-03-17 23:45:48 -05:00
}
toJSON() {
return {
2019-04-28 08:29:01 -05:00
uuid: this.uuid,
uri: this.uri,
2019-03-17 23:45:48 -05:00
};
}
}