Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Diversión con Asincronía #17

Open
UlisesGascon opened this issue Oct 2, 2018 · 1 comment
Open

Diversión con Asincronía #17

UlisesGascon opened this issue Oct 2, 2018 · 1 comment

Comments

@UlisesGascon
Copy link
Contributor

UlisesGascon commented Oct 2, 2018

Notas

Nivel 1

prueba

llamadaAjax(urlAire, (err,dato) => {
	err ? console.warn(err) : console.log(dato);
})

llamadaAjax(url)
	.then(console.log)
	.catch(console.warn)

async function init(){
	try {
		const dato = await llamadaAjax(urlAire)
		console.log(dato)
	} catch(err) {
		console.warn(err)
	}
}

Librería

const urlAire = "http://airemad.com/api/v1/station"

function llamadaAjax(url, cb){
	const promesa = new Promise ((resolve, reject) => {
		fetch(url)
		    .then(request => request.text())
		    .then(text => {
		        resolve(JSON.parse(text));
		    })
		    .catch(error => {
		        reject(error);
		    });
	})

	if(cb && typeof(cb) === "function"){
		promesa
			.then(data => cb(false, data))
			.catch(cb)
	} else {
		return promesa
	}
	
}

Nivel 2

prueba

const servEstaciones = servicioHttp("http://airemad.com/api/v1/")

servEstaciones("station")
    .then(console.log)
    .catch(console.warn)

servEstS001("station/S001", (err, data) => {
   if(err) {
      console.warn(err)  
 } else {
     console.log(data)
}
})

código

function servicioHttp (baseUrl){

	//credetials, tokens, etc..

	return function(endpoint, cb) {

		const promesa = new Promise ((resolve, reject) => {
			fetch(${baseUrl + endpoint})
			    .then(request => request.text())
			    .then(text => {
			        resolve(JSON.parse(text));
			    })
			    .catch(error => {
			        reject(error);
			    });
		})

		if(cb && typeof(cb) === "function"){
			promesa
				.then(data => cb(false, data))
				.catch(cb)
		} else {
			return promesa
		}


	}
}

Nivel 3 🦄

reto

//HEADERS
servicioHttp("http://airemad.com/api/v1/")
	.headers({
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    })
    .method("trace")
    //promesa o cb




// comportamiento para GET, POST, PUT, DELETE
servicioHttp("http://airemad.com/api/v1/")
	.get("station/123")
	.then(console.log)
	.catch(console.warn)

servicioHttp("http://airemad.com/api/v1/")
	.get("station/123", (err, data) => {
		if(err){
			console.warn(err)
		} else {
			console.log(data)
		}

	})


// comportamiento para GET, POST, PUT, DELETE
servicioHttp("http://airemad.com/api/v1/")
	.post("station", {id:123})
	.then(console.log)
	.catch(console.warn)

código

function $http (baseUrl){

	let headers = {}
	function wrapperAjax ({url, method, data}){
		const setup = {}
			setup.method = method;
			setup.headers = headers;
			if(data){
				setup.body = typeof(data) !== "string" ? JSON.stringify(data): data;
			}
		return fetch(`${baseUrl+ url}`, setup)
	}

	function fallbackStrategy (prom, cb) {
		if(cb && typeof(cb) === "function") {
			prom
				.then(response => response.json())
				.then(data => cb(false, data))
				.catch(cb)
		} else {
			return prom.then(response => response.json())
		}
	}

	return {
		headers(obj){
			const _self = this;
			this.headers = obj;
			return _self;
		},
		method(verb, url, data, cb){
			return fallbackStrategy(wrapperAjax({
				url, method:verb, data
			}), cb)
		},
		get(url, cb){
			return fallbackStrategy(wrapperAjax({
				url, method:"GET"
			}), cb)
		},
		post(url, data, cb){
			return fallbackStrategy(wrapperAjax({
				url, method:"POST", data
			}), cb)
		},
		put(url, data, cb){
			return fallbackStrategy(wrapperAjax({
				url, method:"PUT", data
			}), cb)
		},
		delete(url, cb){
			return fallbackStrategy(wrapperAjax({
				url, method:"DELETE"
			}), cb)
		}
	}
}

Test Final

$http("http://airemad.com/api/v1/")
	.get("station/S001")
	.then(console.log)
	.catch(console.warn)
@UlisesGascon
Copy link
Contributor Author

UlisesGascon commented Oct 2, 2018

Pendiente @Xexuline

  • Probar el código y hacer que funcione :trollface:
  • headers necesita un refactor
  • Soporte a XMLHttpRequest
  • Test unitarios con 89% de C

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants