All files index.js

100% Statements 19/19
100% Branches 12/12
100% Functions 3/3
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44      1x           5x 5x   5x 5x   5x     5x 9x 6x 6x     3x         6x 1x     5x 5x 1x 1x   4x 4x        
import consul from 'consul';
import Promise from 'bluebird';
 
const CONSUL_PREFIX = 'consul';
var consulClient;
 
export default class ServerlessConsulVariables {
 
  constructor(serverless) {
    const consulSettings = (serverless.service.custom && serverless.service.custom['serverless-consul-variables']) ? serverless.service.custom['serverless-consul-variables'] : {};
    consulClient = consul({...consulSettings, promisify: true});
 
    this.serverless = serverless;
    this.resolvedValues = {};
 
    const delegate = serverless.variables
      .getValueFromSource.bind(serverless.variables);
 
    serverless.variables.getValueFromSource = (variableString) => {
      if (variableString.startsWith(`${CONSUL_PREFIX}:`)) {
        const variable = variableString.split(`${CONSUL_PREFIX}:`)[1];
        return this._getValueFromConsul(variable);
      }
 
      return delegate(variableString);
    }
  }
 
  async _getValueFromConsul(variable) {
    if (this.resolvedValues[variable]) {
      return Promise.resolve(this.resolvedValues[variable]);
    }
 
    const data = await consulClient.kv.get(variable.startsWith('/') ? variable.substr(1) : variable);
    if (!data) {
      const errorMessage = `Error getting variable from Consul: ${variable}. Variable not found.`;
      throw new this.serverless.classes.Error(errorMessage);
    }
    this.resolvedValues[variable] = data.Value;
    return data.Value;
  }
}