kea-react
Version:
Componentes comunes de react
134 lines (118 loc) • 5.48 kB
text/typescript
import { UrlParameters, UrlParameterScalar, UrlParameterScalarNull, UrlParamValue, encodeUrlParameters } from "./url";
/**Una petición HTTP */
export interface HttpRequest {
/**URL de la petición */
url: string;
/**Metodo de la petición */
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
body?: any;
urlParameters?: UrlParameters<string>;
headers?: UrlParameters<string>;
}
/**Servicio de HTTP */
export class HttpClass {
/**Función de middleware que transforma todas las peticiones HTTP. Si es null el middleware no hara ninguna modificación a la petición. Asignela para aplicar sus propios middleware */
public Middleware: (request: HttpRequest) => (PromiseLike<HttpRequest> | HttpRequest);
/**Perform an http GET. The promise returns the deserialized response body */
public Get = async <TParams extends UrlParameters<keyof TParams>, THeaderParams extends UrlParameters<keyof THeaderParams>>
(url: string, parameters?: TParams, headers?: THeaderParams): Promise<any> => {
return await this.HttpJson({
url: url,
headers: headers as any,
urlParameters: parameters as any,
method: "GET",
});
}
/**Perform an http DELETE. The promise returns the deserialized response body */
public async Delete<TParams extends UrlParameters<keyof TParams>, THeaderParams extends UrlParameters<keyof THeaderParams>>
(url: string, parameters?: TParams, headers?: THeaderParams): Promise<any> {
return await this.HttpJson({
url: url,
headers: headers as any,
urlParameters: parameters as any,
method: "DELETE",
});
}
/**Perform an http POST. The promise returns the deserialized response body */
public async Post<TParams extends UrlParameters<keyof TParams>, THeaderParams extends UrlParameters<keyof THeaderParams>>
(url: string, body: any, parameters?: TParams, headers?: THeaderParams): Promise<any> {
return await this.HttpJson({
url: url,
headers: headers as any,
urlParameters: parameters as any,
body: body,
method: "POST",
});
}
/**Perform an http PUT. The promise returns the deserialized response body */
public async Put<TParams extends UrlParameters<keyof TParams>, THeaderParams extends UrlParameters<keyof THeaderParams>>
(url: string, body: any, parameters?: TParams, headers?: THeaderParams): Promise<any> {
return await this.HttpJson({
url: url,
headers: headers as any,
urlParameters: parameters as any,
body: body,
method: "PUT",
});
}
/**Serialize the body if any and execute an http request. The promise returns the http deserialized json body or a failure with the http status. Returns null if the body response was empty */
public async HttpJson(request: HttpRequest): Promise<any> {
if (request.body) {
request.headers = request.headers || {};
request.headers["Content-Type"] = "application/json;charset=UTF-8";
request.body = JSON.stringify(request.body);
}
var json = await this.Http(request);
if (json) {
try {
return JSON.parse(json);
}
catch (ex) {
throw "Hubo un error al tratar de parsear el JSON de la respuesta HTTP: " + ex;
}
}
else
return null;
}
/**Execute an http request. The promise returns the http body as-is or a failure with the http status */
public async Http(request: HttpRequest): Promise<any> {
if (this.Middleware) {
request = await this.Middleware(request);
}
return await this.HttpNoMiddleware(request);
}
/**Execute an http request. The promise returns the http body as-is or a failure with the http status */
private HttpNoMiddleware(request: HttpRequest): Promise<any> {
const urlParameters = request.urlParameters || {};
const headers = request.headers || {};
const body = request.body;
const method = request.method;
//Assign url parameters:
//Aplanamos los key values que sean arreglos:
const paramsStr = encodeUrlParameters(urlParameters);
const url = paramsStr ? (request.url + "?" + paramsStr) : request.url;
var req = new XMLHttpRequest();
req.open(method, url, true);
for (var key in headers) {
const value = headers[key];
if (value != null)
req.setRequestHeader(key, "" + value);
}
req.send(body);
return new Promise((resolve, reject) => {
req.onreadystatechange = ev => {
if (req.readyState == 4) {
//Todos los status 200 pasan correctamente:
if (req.status >= 200 && req.status < 300) {
resolve(req.response);
} else {
console.error("error loading " + url);
reject(req.status);
}
}
};
});
}
}
/**Servicio HTTP por default */
export var Http = new HttpClass();