refactor: automatic read/load for Resource
This commit is contained in:
parent
ef0b526374
commit
2a9d60006d
|
@ -1,8 +1,35 @@
|
|||
// import axios from 'axios';
|
||||
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 ('undefined' !== typeof window) {
|
||||
return fetch(uri).then((response) => {
|
||||
return response.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);
|
||||
}
|
||||
resolve(JSON.parse(buffer.toString('utf8')));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.uri_PRIVATE = undefined;
|
||||
this.uuid_PRIVATE = undefined;
|
||||
|
@ -47,11 +74,3 @@ export class Resource {
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
Resource.createLoader = function(C) {
|
||||
return (uri) => Resource.read(uri).then((O) => (new C()).fromJSON(O));
|
||||
}
|
||||
|
||||
Resource.read = function(uri) {
|
||||
return axios.get(uri).then(response => response.data);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user