config-req
Axios wrapper based on a config file
How it works
This module allows to set up a programmatic HTTP client based on axios. To set it up, it just the url and the HTTP
method per environment to be setup ¡et voilà!, a new and shiny HTTP client is ready to be used.
Axios options can be found here;
Install package
npm install config-req
Basic Example
const request = require('config-req');
const config = {
activateAccount: {
url: 'http://localhost:5000/v1/account/activate',
method: 'post',
},
};
const api = request(config);
console.log(api);
api.activateAccount()
.then(response => {
console.log(response);
});
Nesting Configuration Example
const request = require('config-req');
const nestedOptions = {
registration: {
activateAccount: {
url: 'http://localhost:5000/v1/account/activate',
method: 'post',
},
},
};
const api = request(nestedOptions);
console.log(api);
api.registration.activateAccount()
.then(response => {
console.log(response);
});
Customizer request parameters
const request = require('config-req');
const options = {
advanced: {
withBodyInfo: {
url: 'http://localhost:5000/v1/account/activate',
method: 'post',
},
withURLParams: {
url: 'http://localhost:5000/v1/account/:id/activate',
method: 'get',
},
withBasicAuth: {
url: 'http://localhost:5000/v1/account/:id/activate',
method: 'get',
auth: { password: 'pwd', username: 'nickname' },
}
},
};
const api = request(options);
api.advanced.withBodyInfo({
body: { example: 'example' },
query: { example: 'example' },
headers: { Authorization: 'Bearer example' },
})
.then(response => {
console.log(response);
});
api.advanced.withURLParams({
body: { example: 'example' },
query: { example: 'example' },
headers: { Authorization: 'Bearer example' },
params: { id: 'urlParam' },
})
.then(response => {
console.log(response);
});
api.advanced.withURLParams({
body: { example: 'example' },
query: { example: 'example' },
headers: { Authorization: 'Bearer example' },
params: { id: 'urlParam' },
auth: { password: 'pwd', username: 'nickname' },
})
.then(response => {
console.log(response);
});
Intercepting requests
In some scenarios, it might be needed to have a fine-grained control on request or the responses. For example, to
refresh a token when it is expired or to handle errors in a specific way. This can be achieved by using
the interceptors option provided by Axios. These interceptors can be set-up
in the following way:
const request = require('config-req');
const config = {
activateAccount: {
url: 'http://localhost:5000/v1/account/activate',
method: 'post',
},
};
const api = request(config, {
interceptors: {
request: (config) => {
return config;
},
response: {
success: (response) => {
return response;
},
error: (error) => {
return Promise.reject(error);
}
}
}
});
How to contribute
To contribute you must send a PR. This is how you can run the project as a developer.
Run as contributor
Install dependencies
npm install
Execute tests
npm run test