{"size": 1047, "ext": "js", "max_stars_repo_path": "lib/cli/load-dotenv.js", "max_stars_repo_name": "Arun-kc/serverless", "max_stars_repo_stars_event_min_datetime": "2021-03-13T17:59:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T17:59:27.000Z", "max_issues_repo_path": "lib/cli/load-dotenv.js", "max_issues_repo_name": "Arun-kc/serverless", "max_issues_repo_issues_event_min_datetime": "2019-11-20T10:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T09:46:15.000Z", "max_forks_repo_path": "lib/cli/load-dotenv.js", "max_forks_repo_name": "Arun-kc/serverless", "max_forks_repo_forks_event_min_datetime": "2021-07-26T07:15:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T07:15:25.000Z"}
{"max_stars_count": 1, "max_issues_count": 17, "max_forks_count": 1, "avg_line_length": 33.7741935484, "max_line_length": 91, "alphanum_fraction": 0.7249283668}
'use strict';

const dotenv = require('dotenv');
const path = require('path');
const ServerlessError = require('../serverless-error');

const isMissingFileError = (error) => error.code === 'ENOENT';

const throwDotenvError = (error, filePath) => {
  const errorMessage = `Failed to load environment variables from "${filePath}": ${error}`;
  throw new ServerlessError(errorMessage, 'DOTENV_LOAD_ERROR');
};

module.exports = (stage) => {
  const defaultEnvFilePath = path.join(process.cwd(), '.env');
  const stageEnvFilePath = path.join(process.cwd(), `.env.${stage}`);

  const { error: stageEnvResultError } = dotenv.config({ path: stageEnvFilePath });

  if (!stageEnvResultError) return;

  if (!isMissingFileError(stageEnvResultError)) {
    throwDotenvError(stageEnvResultError, stageEnvFilePath);
  }

  const { error: defaultEnvResultError } = dotenv.config({ path: defaultEnvFilePath });
  if (defaultEnvResultError && !isMissingFileError(defaultEnvResultError)) {
    throwDotenvError(defaultEnvResultError, defaultEnvFilePath);
  }
};
