awv3
Version:
⚡ AWV3 embedded CAD
54 lines (48 loc) • 1.76 kB
JavaScript
import Parser from '../core/parser';
import Base from './base';
import EventEmitter from 'events';
import { createContext, mergeContext, handleResult } from '../core/parser';
export default class Rest extends Base {
constructor(options) {
super(options);
}
connect(url) {
this.url = this.url || url;
return fetch(`${this.url}/login`).then(res => res.json()).then(res => {
if (res.status === 'permitted') {
this.alive = true;
this.id = res.id;
return this;
}
});
}
disconnect() {
this.alive = false;
this.emit('disconnected');
return fetch(`${this.url}/logout/${this.id}`);
}
request(command, factory) {
return new Promise((resolve, reject) => {
let context = createContext(factory, resolve, reject, command);
context.options.callback({ type: Parser.Factory.Started, context });
return fetch(`${this.url}/execute/${this.id}`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(command)
})
.then(res => res.json())
.then(res => handleResult(context, res))
.then(async res => {
let results = await Promise.all(context.promises);
context = mergeContext(context);
resolve(context);
});
}).then(results => {
results.options.callback({ type: Parser.Factory.Finished, context: results });
return results;
});
}
}