How to use a method without having to import it directly into the file that invokes it?

Asked

Viewed 28 times

0

In one of my files I have the following content:

function env(param, defaultValue) {
  return process.env[param] || defaultValue;
}

module.exports = {
  title: env('TITLE', 'valor padrao'),
  url: env('URL', 'http://localhost'),
  port: env('PORT', 80),
  asset_url: env('ASSET_URL', null),
  time_zone: 'America/Sao_Paulo'
}

How could I separate the section:

// arquivo: config/app.js
module.exports = {
  title: env('TITLE', 'valor padrao'),
  url: env('URL', 'http://localhost'),
  port: env('PORT', 80),
  asset_url: env('ASSET_URL', null),
  time_zone: 'America/Sao_Paulo'
}

In a separate file, and still be able to use the env without having to import it in the configuration file presented above?

1 answer

0

I was able to find a solution to the problem by presenting. The structure was more or less like this:

I created the settings file in /config/app.js:

/** 
 * Centraliza as configurações essenciais do aplicativo.
 * @module configuration/app
*/

module.exports = {
  /**
   * Título da aplicação
   * @type {string}
   */
  name: env('APP_NAME', 'valor padrao'),

  /**
   * Ambiente de aplicação
   * @type {string}
   */
  env: env('APP_ENV', 'production'),

  /**
   * Gerencia o modo debug da aplicação
   * @type {boolean}
   */
  debug: env('APP_DEBUG', false),

  /**
   * URL de acesso a aplicação
   * @type {string}
   */
  url: env('APP_URL', 'http://localhost'),

  /**
   * URL dos asset, arquivos estáticos
   * @type {string|null}
   */
  asset_url: env('ASSET_URL', null),

  /**
   * Porta onde o serviço web estará ouvindo
   * @type {number}
   */
  port: env('PORT', 80),

  /**
   * Zona de fuso horário do aplicativo, formato de data/hora
   * @type {string}
   */
  timezone: 'America/Sao_Paulo'
}

I created a "Helper" in /start/environmentSettings.js:

require('dotenv/config');
const fs = require('fs');
const path = require('path');

global.env = function env(param, defaultValue) {
  return process.env[param.toUpperCase()] || defaultValue;
}

const rootPath = path.resolve(__dirname, '..', '..', 'config');

function config(param) {
  const [file, key] = param.split('.');  

  const pathFile = path.join(rootPath, file + '.js');

  if (fs.existsSync(pathFile)) {
    const config = require(pathFile);
    return config[key];
  }
}

module.exports = config;

In the helper above I am basically creating a global variable env and exporting the method config, which we use to access the settings.

Finally we can test like this:

const config = require('./environmentSettings');

console.log(config('app.title'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.