Skip to content

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 a process.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 en WABOT_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:

ValorMétodoDescripción
developmentisDevelopment()Desarrollo local (default si no se define)
stagingPre-producción
testingisTesting()Ejecución de tests
productionisProduction()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:

VariableTipoDefaultDescripción
WABOT_ENVstringdevelopmentEntorno de ejecución
PORTnumber3000Puerto del servidor HTTP
JWT_SECRETstringClave secreta para JWT (requerida si usas auth)
JWT_ALGORITHMstringHS256Algoritmo de firma JWT
JWT_ACCESS_EXPIRATION_SECONDSnumber600Expiración del access token
JWT_REFRESH_EXPIRATION_SECONDSnumber31536000Expiración del refresh token
SOCKET_CORS_ORIGINstring*Origen CORS para WebSocket
DATABASE_URLstringURL 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.