Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const debug = require('debug')('cenv:api');
- const axios = require('axios');
- /**
- * @class Api
- */
- class Api {
- /**
- * @param {Config} config
- */
- constructor(config) {
- const hasRegistry = !!config.registry;
- const hasToken = !!config.token;
- const hasAuth = (config.username && config.password);
- if (!hasRegistry) throw new Error('Registry ulr must be specified');
- if (!hasToken && !hasAuth) throw new Error('Neither token or user auth was specified');
- const axiosConfig = {
- baseURL: `${config.registry}/v1/`,
- timeout: config.timeout || 1000,
- };
- if (config.token) {
- axiosConfig.headers = { Authorization: `Bearer ${config.token}` };
- }
- this.config = config;
- this.instance = axios.create(axiosConfig);
- }
- /**
- * @return {Boolean}
- */
- get authNeeded() {
- return !this.config.token;
- }
- /**
- * @return {Promise.<TResult>}
- */
- authenticate() {
- if (!this.authNeeded) return Promise.resolve();
- const { username, password } = this.config;
- return this.instance.post('auth', { username, password })
- .then(data => (this.config.token = data.token))
- .catch(() => console.log('passou aqui 1'));
- }
- /**
- * @param {String} name
- * @return {Promise.<TResult>}
- */
- environment(name) {
- debug(`retrieving variables for "${name}" environment`);
- return this.authenticate()
- .then(this.instance.get(`environment/${name}`))
- .catch(() => {});
- }
- }
- new Api({ registry: 'asdasdasd', username: 'asdasd', password: 'asdasd' })
- .environment('asda')
- .catch(() => console.log('passou aqui 2'));
- module.exports = Api;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement