Last active
January 2, 2018 14:12
-
-
Save khanhtdbse/1b4899a3582095c7e0e951f75d01c063 to your computer and use it in GitHub Desktop.
proxy-example.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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