Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Created April 30, 2020 02:33
Show Gist options
  • Save AGhost-7/3295b5350aac40f8d1b51b36a7268dd3 to your computer and use it in GitHub Desktop.
Save AGhost-7/3295b5350aac40f8d1b51b36a7268dd3 to your computer and use it in GitHub Desktop.
import http from './http.mjs';
const createRecipe = http.createRecipe();
createRecipe.request({
name: 'Dhal',
author: 'AGhost-7'
});
if (createRecipe.loading) {
console.log('loading');
}
http.connector = {
createRecipe: () => ({
loading: true
})
};
const createRecipeAlwaysLoading = http.createRecipe();
console.log('loading?', createRecipeAlwaysLoading.loading);
import { defaultConnector } from './http.mjs';
// return back to normal
http.connector = defaultConnector;
const createRecipeReverted = http.createRecipe();
createRecipe.request({
name: 'Pasta alla norma',
author: 'AGhost-7'
});
const requestHook = (requestHandler) => () => {
const [state, setState] = useState({
loading: false,
error: null,
result: null,
request
});
function request(...parameters) {
requestHandler(...parameters)
.then((result) => {
setState({
...state,
loading: false,
result,
error: null,
});
return result;
})
.catch((error) => {
setState({
...state,
loading: false,
error
});
return Promise.reject(error);
});
}
return state;
};
const defaultConnector = {
createRecipe: requestHook((formData) => {
return fetch(formData)
.then((response) => response.json().then((body) => ({ response, body })))
.then(({ response, body }) => {
if (response.status !== 200) {
return Promise.reject(new Error(body));
}
return body;
});
})
};
const handler = {
get(obj, prop) {
return obj.connector[prop];
}
};
const httpClient = new Proxy({ connector: defaultConnector }, handler);
export default httpClient;
export { httpClient, defaultConnector };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment