Variables de Entorno
Wabot proporciona la clase Env para acceder a variables de entorno de forma tipada y segura. Es un singleton que se inyecta automáticamente en cualquier servicio.
Conceptos clave
Env: singleton que encapsula el acceso aprocess.env.requireString(name, options?): obtiene una variable como string (lanza error si no existe y no tiene default).requireNumber(name, options?): obtiene una variable como number.isDevelopment(),isProduction(),isTesting(): verifican el entorno actual basándose enWABOT_ENV.
Lectura de variables
import { Env, singleton } from '@wabot-dev/framework'
@singleton()export class AppConfig { readonly databaseUrl: string readonly port: number readonly apiKey: string readonly maxRetries: number
constructor(env: Env) { // Requerida — lanza error si no existe this.databaseUrl = env.requireString('DATABASE_URL')
// Con valor por defecto this.port = env.requireNumber('PORT', { default: 3000 }) this.apiKey = env.requireString('API_KEY', { default: 'dev-key' }) this.maxRetries = env.requireNumber('MAX_RETRIES', { default: 3 }) }}Entornos de ejecución
La variable WABOT_ENV controla el entorno. Los valores válidos son:
| Valor | Método | Descripción |
|---|---|---|
development | isDevelopment() | Desarrollo local (default si no se define) |
staging | — | Pre-producción |
testing | isTesting() | Ejecución de tests |
production | isProduction() | Producción |
import { Env, injectable } from '@wabot-dev/framework'
@injectable()export class LoggingService { constructor(private env: Env) {}
log(message: string) { if (this.env.isDevelopment()) { console.log(`[DEV] ${message}`) }
if (this.env.isProduction()) { // Enviar a servicio de logging externo this.sendToCloudLogging(message) } }}Variables del framework
Wabot usa estas variables internamente:
| Variable | Tipo | Default | Descripción |
|---|---|---|---|
WABOT_ENV | string | development | Entorno de ejecución |
PORT | number | 3000 | Puerto del servidor HTTP |
JWT_SECRET | string | — | Clave secreta para JWT (requerida si usas auth) |
JWT_ALGORITHM | string | HS256 | Algoritmo de firma JWT |
JWT_ACCESS_EXPIRATION_SECONDS | number | 600 | Expiración del access token |
JWT_REFRESH_EXPIRATION_SECONDS | number | 31536000 | Expiración del refresh token |
SOCKET_CORS_ORIGIN | string | * | Origen CORS para WebSocket |
DATABASE_URL | string | — | URL de conexión a PostgreSQL |
Ejemplo completo
Configurar un servicio que se comporta diferente según el entorno:
import { Env, singleton, Logger } from '@wabot-dev/framework'
@singleton()export class PaymentGateway { private readonly apiUrl: string private readonly apiKey: string private readonly sandbox: boolean private logger = new Logger('wabot:payments')
constructor(env: Env) { this.sandbox = !env.isProduction()
if (env.isProduction()) { this.apiUrl = env.requireString('PAYMENT_API_URL') this.apiKey = env.requireString('PAYMENT_API_KEY') } else { this.apiUrl = env.requireString('PAYMENT_API_URL', { default: 'https://sandbox.payments.example.com', }) this.apiKey = env.requireString('PAYMENT_API_KEY', { default: 'sandbox-test-key', }) }
this.logger.info('PaymentGateway inicializado', { sandbox: this.sandbox, url: this.apiUrl, }) }
async charge(amount: number, currency: string) { if (this.sandbox) { this.logger.debug('Pago simulado (sandbox)', { amount, currency }) return { success: true, transactionId: 'sandbox-' + Date.now() } }
// Lógica real de cobro const response = await fetch(`${this.apiUrl}/charge`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ amount, currency }), })
return await response.json() }}Siguiente paso
Agrega logging estructurado a tu aplicación: Logger.