Classe Module Pattern em EcmaScript/JavaScript para XMLHttpRequest2 - com utiliza??o de Promises

Classe Module Pattern em EcmaScript/JavaScript para XMLHttpRequest2 - com utiliza??o de Promises



Classe completa, escrita em EcmaScript/JavaScript, no padr?o MODULE PATTERN;

O objetivo da classe é utiliza??o generalizada das potencialidades do objeto XmlHttpRequest nível 2 - Ajax;

O código está apropriado com os rigores da biblioteca EcmaScript 262;

O código de acesso assíncrono está aderente ao recurso [Promises].

var classAjax=(function()
	/////////////////////////////////////////////////////////////
	// Propriedade: STATUS
	//? ? ? ? ? ? ? ======
	//variáveis Ajax:
	// 01) SUCCSESSFUL;
	// 02) CLENT ERROR;
	// 03) SERVER ERROR
	/////////////////////////////////////////////////////////////


? ? const __OK=200;? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//The request is OK (this is the standard response for successful HTTP requests)
	const __Created=201;? ? ? ? ? ? ? ? ? ? ? ? //The request has been fulfilled, and a new resource is created
	const __Accepted=202;? ? ? ? ? ? ? ? ? ? ? ?//The request has been accepted for processing, but the processing has not been completed
	const __Non_Authoritative_Information=203;? //The request has been successfully processed, but is returning information that may be from another source
	const __No_Content=204;? ? ? ? ? ? ? ? ? ? ?//The request has been successfully processed, but is not returning any content
	const __Reset_Content=205;? ? ? ? ? ? ? ? ? //The request has been successfully processed, but is not returning any content, and requires that the requester reset the document view
	const __Partial_Content=206;? ? ? ? ? ? ? ? //The server is delivering only part of the resource due to a range header sent by the client


	//Variáveis Ajax - CLIENT ERROR
	const __Bad_Request=400;? ? ? ? ? 	? ? ? ? //The request cannot be fulfilled due to bad syntax
	const __Unauthorized=401;? ? ? ? ? ? ? ? ? ?//The request was a legal request, but the server is refusing to respond to it. For use when authentication is possible but has failed or not yet been provided
	const __Payment_Required=402;? ? ? ? ? ? ? ?//Reserved for future use
	const __Forbidden=403;? ? ? ? ? ? ? ? ? ? ? //The request was a legal request, but the server is refusing to respond to it
	const __Not_Found=404;? ? ? ? ? ? ? ? ? ? ? //The requested page could not be found but may be available again in the future
	const __Method_Not_Allowed=405;? ? ? ? ? ? ?//A request was made of a page using a request method not supported by that page
	const __Not_Acceptable=406;? ? 	? ? ? ? ? ? //The server can only generate a response that is not accepted by the client
	const __Proxy_Authentication_Required=407;? //The client must first authenticate itself with the proxy
	const __Request_Timeout=408;? ? ? ? ? ? ? ? //The server timed out waiting for the request
	const __Conflict=409;? ? ? ? ? ? ? ? ? ? ? ?//The request could not be completed because of a conflict in the request
	const __Gone=410;? ? ? ? ? ? ? ? ? ? ? ? ? ?//The requested page is no longer available
	const __Length_Required=411;? ? ? ? ? ? ? ? //The "Content-Length" is not defined. The server will not accept the request without it
	const __Precondition_Failed=412;? ? ? ? ? ? //The precondition given in the request evaluated to false by the server
	const __Request_Too_Large=413;? ? ? ? ? ? ? //The server will not accept the request, because the request entity is too large
	const __Request_URI_Too_Long=414;? ? ? ? ? ?//The server will not accept the request, because the URI is too long. Occurs when you convert a POST request to a GET request with a long query information
	const __Unsupported_Media_Type=415;? ? ? ? ?//The server will not accept the request, because the media type is not supported
	const __Range_Not_Satisfiable=416;? ? ? ? ? //The client has asked for a portion of the file, but the server cannot supply that portion
	const __Expectation_Failed=417;? ? ? ? ? ? ?//The server cannot meet the requirements of the Expect request-header field


	//Variáveis Ajax - SERVER ERROR
	const __Internal_Server_Error=500;? ? ? ? ? //A generic error message, given when no more specific message is suitable
	const __Not_Implemented=501;? ? ? ? ? ? ? ? //The server either does not recognize the request method, or it lacks the ability to fulfill the request
	const __Bad_Gateway=502;? ? ? ? ? ? ? ? ? ? //The server was acting as a gateway or proxy and received an invalid response from the upstream server
	const __Service_Unavailable=503;? ? ? ? ? ? //The server is currently unavailable (overloaded or down)
	const __Gateway_Timeout=504;? ? ? ? ? ? ? ? //The server was acting as a gateway or proxy and did not receive a timely response from the upstream server
	const __HTTP_Version_Not_Supported=505;? ? ?//The server does not support the HTTP protocol version used in the request
	const __Network_Authentication_Required=506;//The client needs to authenticate to gain network access




	/////////////////////////////////////////////////////////////
	// Propriedade: readySTATe
	//? ? ? ? ? ? ? ======
	// Retem o status de XMLHttpRequest.
	/////////////////////////////////////////////////////////////


	const __request_not_initialized=0;
	const __server_connection_established=1;
	const __request_received=2;
	const __processing_request=3;
	const __request_finished_and_response_is_ready=4;




	////////////////////////////////////////////////////////////
	// Cabe?alhos - CONTENTTYPE
	////////////////////////////////////////////////////////////


	const __any_kind_of_binary_data="application/octet-stream";
	const __shell_script="application/x-csh";
	const __cascading_Style_Sheets="text/css";														? ? ? ? ? ? ? //css
	const __comma_separated_values="text/csv";	 												? ? ? ? ? ? ? ? ? //csv
	const __hyperText_Markup_Language="text/html";? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //HTML
	const __javaScript="text/javascript";															? ? ? ? ? ? ? //js
	const __jSON_format="application/json";															? ? ? ? ? ? ? //json
	const __adobe_Portable_Document_Format="application/pdf";										? ? ? ? ? ? ? //pdf
	const __rich_Text_Format="application/rtf"? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //rtf
	const __text="text/plain";? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //txt
	const __xhtml="application/xhtml+xml"																		? //xhtml


	//headers
	const __aspDefault="text/html;charset=UTF-8"																? //asp - DEFAULT
	const __asp="application/x-www-form-urlencoded"																? //asp
	const __aspHTML="multipart/form-data"																		? //asp/HTML


	//Microsoft Office
	const __microsoft_Word="application/msword";? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //doc
	const __microsoft_Word="application/vnd.openxmlformats-officedocument.wordprocessingml.document"? ? ? ? ? ? ? //docx
	const __microsoft_Excel="application/vnd.ms-excel"															? //xls
	const __microsoft_Excel_XML="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"? ? ? ? ? ? ? ?//xhtml
	const __microsoft_PowerPoint="application/vnd.ms-powerpoint";? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//ppt
	const __microsoft_PowerPoint_XML="application/vnd.openxmlformats-officedocument.presentationml.presentation"? //pptx




	////////////////////////////////////////////////////////////
	// READYSTATE
	////////////////////////////////////////////////////////////


	const __UNSENT=0;	? ? ? ? ? ?//Client has been created. open() not called yet.
	const __OPENED=1;	? ? ? ? ? ?//open() has been called.
	const __HEADERS_RECEIVED=2	? ?//send() has been called, and headers and status are available.
	const __LOADING_DOWNLOADING=3? //responseText holds partial data.
	const __DONE=4;	? ? ? ? ? ? ? ?//The operation is complete.


	////////////////////////////////////////////////////////////
	// Variáveis locais à classe
	////////////////////////////////////////////////////////////


	let _metodo;? ? ? ? ?//Método default por ser mais robusto e por n?o possuir limite em tamanho da mensagem a ser repassada para os ervidor.
	let _url;? ? ? ? ? ? //nome do programa a ser invocado no servidor (Ex. arquivo txt; ASP; PHP etc)
	let _tipoAsync;? ? ? //TRUE - conex?o assíncrona (DEFAULT) ou FALSE - conex?o síncrona
	let _contentType;? ? //Cabe?alho para as páginas
	let _getParametro;? ?//Lista de parametros para o método GET
	let _tipoResponse;? ?//O response poderá ser "text", "arraybuffer", "blob" ou "document" (responseText ou responseXML)


	//construtor
	var classAjax=function(){
					_metodo = "POST";? ? ? ? ? ? ? ? ? ? ? ?//Método default por ser mais robusto e por n?o possuir limite em tamanho da mensagem a ser repassada para os ervidor.
					_url=null;? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //Nome do programa a ser invocado no servidor (Ex. arquivo txt; ASP; PHP etc)
					_tipoAsync=true;? ? ? ? ? ? ? ? ? ? ? ? //TRUE - conex?o assíncrona ou FALSE - conex?o síncrona
					_contentType=__aspDefault;? ? ? ? ? ? ? //Padr?o ASP mais usual
					_getParametro=null;						//default é NULL por n?o ser obrigatório
					_tipoResponse="text";? 				? ? //Indica responseText - DEFAULT


				? ? //(_servicosErros=new _tratamentoErros());
	};


	classAjax.prototype={
		setIMetodo:function(parametro){
								///////////////////////////////////////////////////////////////////////////
								// Método: público
								//?
								// Op??es possíveis:
								//
								//? ?01) GET;
								//? ?02) POST (default)
								///////////////////////////////////////////////////////////////////////////
								try{
									if(parametro){
										if(
											(parametro.toUpperCase()==="GET") ||
											(parametro.toUpperCase()==="POST")
										){
											(_metodo = parametro);	
										 }		
									}	
								}
								catch(excecao){
										//(_servicosErros.alimentaLog("[{'Problema':'" + excecao.message + "'},{'Método':'setMetodo'}]"));											
								}
		},
		setURL:function(parametro){
								///////////////////////////////////////////////////////////////////////////
								// Método: público
								//
								///////////////////////////////////////////////////////////////////////////
								try{
									if(parametro){
										(_URL = parametro);	
									}	
								}
								catch(excecao){
									//(_servicosErros.alimentaLog("[{'Problema':'" + excecao.message + "'},{'Método':'setURL'}]"));											
								}
		},
		setAsync:function(parametro){
								///////////////////////////////////////////////////////////////////////////
								// Método: público
								//?
								// Op??es possíveis:
								//
								//? ?01) TRUE; (default) - assíncrona
								//? ?02) FALSE? ? ? ? ? ?- síncrona
								///////////////////////////////////////////////////////////////////////////
								try{
									if(parametro){
										if(
											(parametro.toUpperCase()===TRUE) ||
											(parametro.toUpperCase()===FALSE)
										){
											(_tipoAsync = parametro);	
										 }
									}	
								}
								catch(excecao){
									//(_servicosErros.alimentaLog("[{'Problema':'" + excecao.message + "'},{'Método':'setTipoConexao'}]"));											
								}
		},
		setContentType:function(parametro){
								//////////////////////////////////////////////////////////////////////////////////////
								// Método: público
								//
								// Padr?o mais usual para ASP (por isso, default):
								//? ? >> "text/html;charset=UTF-8"
								/////////////////////////////////////////////////////////////////////////////////////
								try{
									if(parametro){
										(_contentType = parametro);	
									}	
								}
								catch(excecao){
									//(_servicosErros.alimentaLog("[{'Problema':'" + excecao.message + "'},{'Método':'setContentType'}]"));											
								}
		},
		setGetParametros:function(parametro){
								//////////////////////////////////////////////////////////////////////////////////////
								// Método: público
								//
								// >> Parametros para o métodom GET.
								// >> Opcional
								//
								// Observa??o:
								// O parametro repassado deverá ser um dos rlacionados abaixo:
								//
								// >> Blob;? ? ? ? ? ?[imagens]
								// >> BufferSource;
								// >> FormData;? ? ? ?[Objeto formData (key:value)]
								// >> URLSearchParams [?variavel1=&variavel2=]
								//?
								// _getParametro deverá receber umm dos objetos acima.?
								/////////////////////////////////////////////////////////////////////////////////////
								try{
									if(parametro){
										(_getParametro = parametro);	
									}	
								}
								catch(excecao){
									//(_servicosErros.alimentaLog("[{'Problema':'" + excecao.message + "'},{'Método':'setGetParametros'}]"));											
								}								
		},
		setTipoResponse:function(parametro){
								///////////////////////////////////////////////////////////////////////////
								// Método: público
								//?
								// Op??es possíveis:
								//
								//? ?01) TEXT; (DEFAULT)
								//? ?02) XML
								///////////////////////////////////////////////////////////////////////////
								try{
									if(parametro){
										if(
											(parametro.toUpperCase()==="TEXT") ||
											(parametro.toUpperCase()==="XML")
										){
											(_metodo = parametro);	
										 }		
									}	
								}
								catch(excecao){
									//(_servicosErros.alimentaLog("[{'Problema':'" + excecao.message + "'},{'Método':'setTipoResponse'}]"));											
								}																										


		},
		invocarServidor:function(){
								try{
									return new Promise(function(resolve, rejeita) {
											
										let _requisicao=null;


										if(window.XMLHttpRequest){
										? ?(_requisicao=new XMLHttpRequest());
										}?
										else if (window.ActiveXObject){
											try {
											? (_requisicao=new ActiveXObject("Msxml2.XMLHTTP"));
											}
											catch(excecao) {
											? ? try {
												? ?(_requisicao=new ActiveXObject("Microsoft.XMLHTTP"));
												}
												catch(excecao){
									? ? ? ? ? ? ? ?//(_servicosErros.alimentaLog("[{'Problema':' + excecao.message + '},{'Método':'setTipoResponse'}]"));											
												}? ?
											}
										}												? ?


										_requisicao.addEventListener('readystatechange', (_progressEvent)=>{
												try{
													if (
														(_requisicao.status==__DONE) ||
														(
														? (_requisicao.status>=__OK) &&
														? (_requisicao.status<__BAD_REQUEST)
														)
													? ?)
													{
													? ?	// Response bem sucedido - retornado do servidor
														if(_tipoResponse.toUpperCase()==="TEXT"){? ?
														? (resolve(_requisicao.responseText));													? ?
														}
														else if(_tipoResponse.toUpperCase()==="DOCUMENT"){
														? (resolve(_requisicao.responseXML));													? ?																
														}??
														else if(_tipoResponse.toUpperCase()==="ARRAYBUFFER"){
														? (resolve(_requisicao.response));													? ?																
														}
														else if(_tipoResponse.toUpperCase()==="BLOB"){
														? (resolve(_requisicao.response));	
														}
													}
												}
												catch(excecao){
													 (rejeita("Problema:Erro na execu??o do código - método [readyStateChange]."));													
												}	
										});												


										_requisicao.addEventListener('loadstart', (_event)=>{
											//chamar gif de progresso
										});


										_requisicao.addEventListener('load', (_event)=>{
										});


										_requisicao.addEventListener('progress', (_progressEvent)=>{
											if(_progressEvent.lengthComputable) {
												//(_progresEvent.total? ?- valor máximo);
												//(_progressEvent.loaded - valor já carregado);?
											}
										});


										_requisicao.addEventListener('loadend', (_ProgressEvent)=>{
											//(_progressEvent.loaded - fim da carga);
											//cancelar gif de progresso
										});												


										_requisicao.addEventListener('error', (_event)=>{
											//cancelar gif de progresso														


											(rejeita("Problema:Erro na execu??o de código em evento [error] registrado."));													
										});


										_requisicao.addEventListener('abort', (_event)=>{
											//cancelar gif de progresso														


											(rejeita("Problema:Aborto espontaneo da execu??o de código em evento [abort] registrado."));
										});


										(_requisicao.open(_metodo, _url, _tipoAsync));
										(_requisicao.setRequestHeader("Content-type", _contentType));
										(_requisicao.responseType=_tipoResponse);


										if(_metodo.toUpperCase()==="GET"){
										? (_requisicao.send(null));
										else if(
											? ? (_metodo.toUpperCase()==="POST") ||
												(_metodo.toUpperCase()==="PUT"){
												////////////////////////////////////////////////////////////////////////
												// Com o método POST, é possíel enviar os seguintes tipos de arquivos:
												//
												// >> Blob;? ? ? ? ? ?[imagens]
												// >> BufferSource;
												// >> FormData;? ? ? ?[Objeto formData (key:value)]
												// >> URLSearchParams [?variavel1=&variavel2=]
												//?
												// _getParametro deverá receber umm dos objetos acima.?
												////////////////////////////////////////////////////////////////////////	
												(_requisicao.send(_getParametro)); 	
										}??


									})
								}
								catch(excecao){	


								}
		}


		return classAjax;							


})();{        

要查看或添加评论,请登录

Otávio Guimar?es的更多文章

社区洞察

其他会员也浏览了