@btfuse/core
Version:
A native-first framework for building hybdrid web-native applications
78 lines (75 loc) • 2.74 kB
JavaScript
;
/*
Copyright 2023 Breautek
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPFuseAPI = void 0;
const ContentType_1 = require("./ContentType");
const FuseAPI_1 = require("./FuseAPI");
const FuseAPIResponse_1 = require("./FuseAPIResponse");
const FuseError_1 = require("./FuseError");
/**
* A Fuse API implementation that uses HTTP protocol to make native calls
*/
class HTTPFuseAPI extends FuseAPI_1.FuseAPI {
async _getEndpoint() {
return '';
}
async _initHeaders(xhr) { }
async buildRoute(pluginID, method) {
const endpoint = await this._getEndpoint();
return `${endpoint}${this._createRoute(pluginID, method)}`;
}
async _execute(pluginID, method, contentType, data) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.open('POST', await this.buildRoute(pluginID, method));
if (!contentType) {
contentType = ContentType_1.ContentType.BINARY;
}
if (contentType) {
xhr.setRequestHeader('Content-Type', contentType);
}
await this._initHeaders(xhr);
return await this._doRequest(xhr, data);
}
_doRequest(xhr, data) {
return new Promise((resolve, reject) => {
xhr.onload = async () => {
const response = new FuseAPIResponse_1.FuseAPIResponse(xhr.response, xhr.getAllResponseHeaders(), xhr.status);
if (response.isError()) {
reject(await response.readAsError());
}
else {
resolve(response);
}
};
xhr.onerror = (e) => {
reject(new FuseError_1.FuseError('FuseAPI', 'Network Error'));
};
xhr.ontimeout = (e) => {
reject(new FuseError_1.FuseError('FuseAPI', 'API Timeout'));
};
this._doSend(xhr, data);
});
}
_doSend(xhr, data) {
if (data !== undefined && data !== null) {
xhr.send(data);
}
else {
xhr.send();
}
}
}
exports.HTTPFuseAPI = HTTPFuseAPI;
//# sourceMappingURL=HTTPFuseAPI.js.map