Skip to content

Instantly share code, notes, and snippets.

@khanhtdbse
Last active January 2, 2018 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanhtdbse/1b4899a3582095c7e0e951f75d01c063 to your computer and use it in GitHub Desktop.
Save khanhtdbse/1b4899a3582095c7e0e951f75d01c063 to your computer and use it in GitHub Desktop.
proxy-example.js
// Reference: https://medium.com/@alonronin/magic-methods-in-javascript-meet-proxy-65e6305f4d3e. Thank for awesome article
const axios = require('axios');
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com/'
});
const target = {};
const handler = {
get(target, name) {
return Object.assign(
{},
[
'get',
'delete',
'head'
].reduce(
(o, method) => Object.assign({}, o, {
[method](url = '', params = {}) {
if (typeof url === 'object') {
params = url;
url = '';
}
return instance[method](name + url, { params });
}
}), {}),
[
'post',
'put',
'patch'
].reduce(
(o, method) => Object.assign({}, o, {
[method](url = '', body = {}, params = {}) {
if (typeof url === 'object') {
params = body;
body = url;
url = '';
}
return instance[method](name + url, body, { params });
}
}), {})
);
}
};
const api = new Proxy(target, handler);
const response = ({ data }) => console.log(data);
api.posts.get().then(response);
api.posts.get({ userId: 10 }).then(response);
api.posts.get('/1/comments', { email: 'Lew@alysha.tv' }).then(response);
const body = {
title: 'test',
body: 'lorem ipsum',
userId: 10,
};
api.posts.post(body).then(response);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment