@akala/core
Version:
243 lines • 10.3 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var FetchHttp_1;
import { each, map } from './each.js';
import { service } from './service.js';
import { formatters } from './formatters/index.js';
import { defaultInjector } from './injectors/simple-injector.js';
import { MiddlewareCompositeAsync } from './middlewares/composite-async.js';
defaultInjector.register('$http-interceptors', new MiddlewareCompositeAsync('$http-interceptors'));
let FetchHttp = FetchHttp_1 = class FetchHttp {
interceptor;
constructor(interceptor) {
this.interceptor = interceptor;
}
/**
* Sends a GET request to the specified URL.
* @param url The URL to request.
* @param params Query parameters to append.
* @returns A promise resolving to the HTTP response.
*/
get(url, params) {
return this.call({ url: url, method: 'GET', queryString: params });
}
/**
* Sends a POST request with a body.
* @param url The target URL.
* @param body The request body.
* @returns A promise resolving to form data from the response.
*/
post(url, body) {
return this.call({ method: 'POST', url: url, body: body }).then(r => {
return r.formData();
});
}
/**
* Sends a JSON POST request.
* @param url The target URL.
* @param body The JSON body content.
* @returns A promise resolving to the parsed JSON response.
*/
postJSON(url, body) {
return this.call({ method: 'POST', url: url, body: body, contentType: 'json', type: 'json' }).then((r) => {
return r.json();
});
}
/**
* Sends a GET request expecting JSON response.
* @param url The target URL.
* @param params Query parameters to include.
* @returns A promise resolving to the parsed JSON data.
*/
getJSON(url, params) {
return this.call({ method: 'GET', url: url, queryString: params, type: 'json' }).then((r) => {
return r.json();
});
}
/**
* Sends a SOAP-based POST request.
* @param namespace SOAP namespace.
* @param action SOAP action name.
* @param url The target URL.
* @param params SOAP parameters.
* @returns A promise resolving to the SOAP response.
*/
invokeSOAP(namespace, action, url, params) {
let body = '<?xml version="1.0" encoding="utf-8"?><s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body>' +
'<u:' + action + ' xmlns:u="' + namespace + '">';
each(params ?? {}, function (paramValue, paramName) {
body += `<${paramName}>${paramValue}</${paramName}>`;
});
body += '</u:' + action + '></s:Body></s:Envelope>';
return this.call({ method: 'POST', url: url, type: 'xml', headers: { 'content-type': 'text/xml', SOAPAction: `"${namespace}#${action}"` }, body: body });
}
/**
* Sends a custom HTTP request using options.
* @param options Configuration for the request.
* @returns A promise resolving to the HTTP response.
*/
call(options) {
const init = { method: options.method || 'GET', body: options.body, redirect: 'manual' };
if (typeof (options.url) == 'string')
options.url = new URL(options.url, globalThis.document?.baseURI);
const url = options.url;
if (options.queryString) {
if (typeof (options.queryString) == 'string')
options.queryString = new URLSearchParams(options.queryString);
options.queryString.forEach((value, name) => url.searchParams.append(name.toString(), value));
}
if (options.headers) {
init.headers = {};
each(options.headers, function (value, key) {
if (value instanceof Date)
init.headers[key] = value.toJSON();
else
init.headers[key] = value && value.toString();
});
}
if (options.type) {
init.headers = init.headers || {};
switch (options.type) {
case 'json':
init.headers['Accept'] = 'application/json, text/json';
if (!options.contentType && typeof (init.body) !== 'string')
init.body = JSON.stringify(init.body);
break;
case 'xml':
init.headers['Accept'] = 'text/xml';
break;
case 'text':
init.headers['Accept'] = 'text/plain';
if (!options.contentType && typeof (init.body) !== 'string')
init.body = init.body.toString();
break;
}
}
if (options.contentType && options.body) {
init.headers = init.headers || {};
switch (options.contentType) {
case 'json':
init.headers['Content-Type'] = 'application/json; charset=UTF-8';
if (typeof (init.body) !== 'string')
init.body = JSON.stringify(init.body);
break;
case 'form-urlencoded':
init.headers['Content-Type'] = 'application/x-www-form-urlencoded';
if (!(init.body instanceof FormData) && typeof init.body !== 'undefined')
init.body = FetchHttp_1.serialize(init.body);
break;
case 'form':
init.headers['Content-Type'] = 'multipart/form-data';
if (!(init.body instanceof FormData) && typeof init.body !== 'undefined')
init.body = FetchHttp_1.serialize(init.body);
break;
}
}
return this.fetch(new Request(options.url, init));
}
async fetch(req) {
if (this.interceptor) {
const r = await this.interceptor.handle(req, null).then(err => {
if (err)
throw err;
}, r => r);
if (r)
return r;
}
const res = await fetch(req);
if (this.interceptor) {
const r = await this.interceptor.handle(req, res).then(err => {
if (err)
throw err;
}, r => r);
if (r)
return r;
}
if (res.status == 302 || res.status == 301) {
req.headers.set('cookie', res.headers.get('set-cookie'));
return await this.fetch(new Request(new URL(res.headers.get('Location'), req.url), req));
}
if (this.interceptor) {
const r = await this.interceptor.handle(req, res).then(err => {
if (err)
throw err;
}, r => r);
if (r)
return r;
}
return res;
}
/**
* Serializes an object into URL-encoded format.
*/
static serialize(obj, prefix) {
if (obj instanceof URLSearchParams)
if (!prefix)
return obj.toString();
else
return this.serialize(Object.fromEntries(obj.entries()), prefix);
if (globalThis.FormData && obj instanceof globalThis.FormData) {
if (!prefix)
return obj;
return this.serialize(Object.fromEntries(obj.entries()), prefix);
}
return map(obj, function (value, key) {
switch (typeof (value)) {
case 'object':
{
if (value === null)
return (prefix || '') + encodeURIComponent(key) + '=';
let keyPrefix = prefix;
if (prefix) {
if (typeof (key) == 'number')
keyPrefix = prefix.substring(0, prefix.length - 1) + '[' + key + '].';
else
keyPrefix = prefix + encodeURIComponent(key) + '.';
}
return FetchHttp_1.serialize(value, keyPrefix);
}
case 'undefined':
return '';
default:
return (prefix || '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
}
}, true).join('&');
}
};
FetchHttp = FetchHttp_1 = __decorate([
service('$http', '$http-interceptors'),
__metadata("design:paramtypes", [Object])
], FetchHttp);
export { FetchHttp };
export class HttpCallFormatter {
settings;
previousValue;
previousCall;
constructor(settings) {
this.settings = settings;
}
format(scope) {
const settings = this.settings;
if (this.previousValue === scope)
return this.previousCall;
this.previousValue = scope;
return this.previousCall = defaultInjector.injectWithName(['$http'], function (http) {
const formattedValue = scope;
if (typeof (formattedValue) == 'string' || formattedValue instanceof URL)
if (settings)
return http.call({ ...settings, url: formattedValue });
else
return http.call({ method: 'GET', type: 'json', url: formattedValue });
return http.call(formattedValue);
})();
}
}
formatters.register('http', HttpCallFormatter);
//# sourceMappingURL=http.js.map