Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const debug = require('debug')('cenv:api');
  2. const axios = require('axios');
  3.  
  4. /**
  5.  * @class Api
  6.  */
  7. class Api {
  8.   /**
  9.    * @param {Config} config
  10.    */
  11.   constructor(config) {
  12.     const hasRegistry = !!config.registry;
  13.     const hasToken = !!config.token;
  14.     const hasAuth = (config.username && config.password);
  15.  
  16.     if (!hasRegistry) throw new Error('Registry ulr must be specified');
  17.     if (!hasToken && !hasAuth) throw new Error('Neither token or user auth was specified');
  18.  
  19.     const axiosConfig = {
  20.       baseURL: `${config.registry}/v1/`,
  21.       timeout: config.timeout || 1000,
  22.     };
  23.     if (config.token) {
  24.       axiosConfig.headers = { Authorization: `Bearer ${config.token}` };
  25.     }
  26.  
  27.     this.config = config;
  28.     this.instance = axios.create(axiosConfig);
  29.   }
  30.  
  31.   /**
  32.    * @return {Boolean}
  33.    */
  34.   get authNeeded() {
  35.     return !this.config.token;
  36.   }
  37.  
  38.   /**
  39.    * @return {Promise.<TResult>}
  40.    */
  41.   authenticate() {
  42.     if (!this.authNeeded) return Promise.resolve();
  43.  
  44.     const { username, password } = this.config;
  45.     return this.instance.post('auth', { username, password })
  46.       .then(data => (this.config.token = data.token))
  47.       .catch(() => console.log('passou aqui 1'));
  48.   }
  49.  
  50.   /**
  51.    * @param {String} name
  52.    * @return {Promise.<TResult>}
  53.    */
  54.   environment(name) {
  55.     debug(`retrieving variables for "${name}" environment`);
  56.  
  57.     return this.authenticate()
  58.       .then(this.instance.get(`environment/${name}`))
  59.       .catch(() => {});
  60.   }
  61. }
  62.  
  63. new Api({ registry: 'asdasdasd', username: 'asdasd', password: 'asdasd' })
  64.   .environment('asda')
  65.   .catch(() => console.log('passou aqui 2'));
  66.  
  67. module.exports = Api;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement