🔧 Odac.Var - Manipulación y validación de cadenas
Odac.Var es una potente clase de utilidad para manipular, validar, cifrar y formatear cadenas. Ofrece una interfaz fluida y encadenable para operaciones comunes con cadenas.
Uso básico
// Create a Var instance
const result = Odac.Var('hello world').slug()
// Returns: 'hello-world'
Validación de cadenas
Comprueba si una cadena coincide con patrones específicos:
is() - Validación individual
// Email validation
Odac.Var('user@example.com').is('email') // true
Odac.Var('invalid-email').is('email') // false
// Numeric validation
Odac.Var('12345').is('numeric') // true
Odac.Var('abc123').is('numeric') // false
// Multiple conditions (AND logic)
Odac.Var('abc123').is('alphanumeric') // true
isAny() - Validación múltiple (lógica OR)
// Check if value matches ANY of the conditions
Odac.Var('user@example.com').isAny('email', 'domain') // true
Odac.Var('example.com').isAny('email', 'domain') // true
Tipos de validación disponibles
'alpha' // Only letters (A-Z, a-z)
'alphaspace' // Letters and spaces
'alphanumeric' // Letters and numbers
'alphanumericspace' // Letters, numbers, and spaces
'username' // Alphanumeric only (no spaces)
'hash' // scrypt hash format ($scrypt$)
'date' // Valid date string
'domain' // Valid domain name (example.com)
'email' // Valid email address
'float' // Floating point number
'host' // IP address / Host
'ip' // IP address
'json' // Valid JSON string
'mac' // MAC address
'md5' // 32-char MD5 hash
'numeric' // Numbers only
'url' // Valid URL (protocol + domain)
'emoji' // Contains emoji characters
'xss' // XSS-safe (no HTML tags)
Ejemplos prácticos
// Controller validation
module.exports = async function(Odac) {
const email = Odac.Request.post('email')
if (!Odac.Var(email).is('email')) {
return Odac.return({
success: false,
message: 'Invalid email address'
})
}
// Continue with valid email
}
Comprobación de cadenas
contains() - Comprobar si la cadena contiene valores
// Single value
Odac.Var('hello world').contains('world') // true
Odac.Var('hello world').contains('foo') // false
// Multiple values (AND logic - must contain all)
Odac.Var('hello world').contains('hello', 'world') // true
Odac.Var('hello world').contains('hello', 'foo') // false
containsAny() - Comprobar si la cadena contiene algún valor
// Check if contains ANY of the values (OR logic)
Odac.Var('hello world').containsAny('foo', 'world') // true
Odac.Var('hello world').containsAny('foo', 'bar') // false
isBegin() - Comprobar si la cadena empieza por un valor
Odac.Var('hello world').isBegin('hello') // true
Odac.Var('hello world').isBegin('world') // false
// Multiple options
Odac.Var('https://example.com').isBegin('http://', 'https://') // true
isEnd() - Comprobar si la cadena termina en un valor
Odac.Var('hello world').isEnd('world') // true
Odac.Var('hello world').isEnd('hello') // false
// Multiple options
Odac.Var('image.jpg').isEnd('.jpg', '.png', '.gif') // true
Manipulación de cadenas
replace() - Reemplazar texto
// Simple replacement
Odac.Var('hello world').replace('world', 'universe')
// Returns: 'hello universe'
// Multiple replacements with object
Odac.Var('Hello {{name}}, welcome to {{site}}').replace({
'{{name}}': 'John',
'{{site}}': 'Odac'
})
// Returns: 'Hello John, welcome to Odac'
// Every occurrence is replaced; values are inserted literally ($& is not a pattern)
Odac.Var('{{name}} and {{name}}').replace({'{{name}}': 'Jo'})
// Returns: 'Jo and Jo'
// Works with arrays/objects recursively
const data = {
title: 'Welcome {{name}}',
message: 'Hello {{name}}'
}
Odac.Var(data).replace({'{{name}}': 'John'})
// Returns: { title: 'Welcome John', message: 'Hello John' }
clear() - Eliminar cadenas específicas
Odac.Var('hello-world-test').clear('-')
// Returns: 'helloworldtest'
// Remove multiple strings
Odac.Var('a1b2c3').clear('1', '2', '3')
// Returns: 'abc'
slug() - Crear un slug amigable para URL
Odac.Var('Hello World!').slug()
// Returns: 'hello-world'
Odac.Var('Product Name 2024').slug()
// Returns: 'product-name-2024'
// Custom separator
Odac.Var('Hello World').slug('_')
// Returns: 'hello_world'
// Accented and Turkish letters are transliterated, not dropped
Odac.Var('Çağrı Şükür').slug()
// Returns: 'cagri-sukur'
format() - Formatear una cadena con un patrón
// ? = single character, * = rest of string
Odac.Var('1234567890').format('(???) ???-????')
// Returns: '(123) 456-7890'
Odac.Var('TR1234567890').format('?? *')
// Returns: 'TR 1234567890'
html() - Escapar HTML
Odac.Var('<script>alert("xss")</script>').html()
// Returns: '<script>alert("xss")</script>'
Cifrado y hashing
hash() - Hashing seguro de contraseñas con scrypt
// Hash a password using enterprise-grade scrypt
const hashedPassword = Odac.Var('mypassword').hash()
// Returns: '$scrypt$[salt]$[hash]'
hashCheck() - Verificar un hash scrypt
const hashedPassword = '$scrypt$...'
const isValid = Odac.Var(hashedPassword).hashCheck('mypassword')
// Returns: true or false
md5() - Hash MD5
Odac.Var('hello').md5()
// Returns: '5d41402abc4b2a76b9719d911017c592'
encrypt() - Cifrado AES-256
// Uses key from Odac.Config.encrypt.key
const encrypted = Odac.Var('secret data').encrypt()
// Custom encryption key
const encrypted = Odac.Var('secret data').encrypt('a-long-random-secret')
decrypt() - Descifrado AES-256
// Uses key from Odac.Config.encrypt.key
const decrypted = Odac.Var(encryptedData).decrypt()
// Custom decryption key
const decrypted = Odac.Var(encryptedData).decrypt('a-long-random-secret')
Formato de fechas
date() - Formatear cadenas de fecha
const timestamp = '2024-03-15 14:30:45'
Odac.Var(timestamp).date('Y-m-d')
// Returns: '2024-03-15'
Odac.Var(timestamp).date('d/m/Y')
// Returns: '15/03/2024'
Odac.Var(timestamp).date('H:i:s')
// Returns: '14:30:45'
Odac.Var(timestamp).date('Y-m-d H:i')
// Returns: '2024-03-15 14:30'
Tokens de formato:
Y- Año de 4 dígitos (2024)y- Año de 2 dígitos (24)m- Mes con cero inicial (01-12)d- Día con cero inicial (01-31)H- Hora con cero inicial (00-23)i- Minuto con cero inicial (00-59)s- Segundo con cero inicial (00-59)
Operaciones con archivos
save() - Guardar una cadena en un archivo
// Save content to file
Odac.Var('Hello World').save('/path/to/file.txt')
// Automatically creates directories if needed
Odac.Var(jsonData).save('/path/to/nested/dir/data.json')
Ejemplos prácticos
Registro de usuario con validación
module.exports = async function(Odac) {
const email = Odac.Request.post('email')
const password = Odac.Request.post('password')
const username = Odac.Request.post('username')
// Validate email
if (!Odac.Var(email).is('email')) {
return Odac.return({
success: false,
message: 'Invalid email address'
})
}
// Validate username (alphanumeric only)
if (!Odac.Var(username).is('alphanumeric')) {
return Odac.return({
success: false,
message: 'Username must be alphanumeric'
})
}
// Hash password
const hashedPassword = Odac.Var(password).hash()
// Create slug for profile URL
const profileSlug = Odac.Var(username).slug()
// Save user
await Odac.DB.users.insert({
email: email,
username: username,
password: hashedPassword,
slug: profileSlug
})
return Odac.return({success: true})
}
Inicio de sesión con verificación de contraseña
module.exports = async function(Odac) {
const email = Odac.Request.post('email')
const password = Odac.Request.post('password')
// Find user
const user = await Odac.DB.users
.where('email', email)
.first()
if (!user) {
return Odac.return({
success: false,
message: 'User not found'
})
}
// Verify password
const isValid = Odac.Var(user.password).hashCheck(password)
if (!isValid) {
return Odac.return({
success: false,
message: 'Invalid password'
})
}
// Login successful
Odac.Auth.login(user.id)
return Odac.return({success: true})
}
Generación de slugs para URL
module.exports = async function(Odac) {
const title = Odac.Request.post('title')
// Create URL-friendly slug
const slug = Odac.Var(title).slug()
// Check if slug exists
const exists = await Odac.DB.posts
.where('slug', slug)
.first()
if (exists) {
// Add timestamp to make unique
const uniqueSlug = `${slug}-${Date.now()}`
await Odac.DB.posts.insert({
title: title,
slug: uniqueSlug
})
} else {
await Odac.DB.posts.insert({
title: title,
slug: slug
})
}
return Odac.return({success: true})
}
Reemplazo de variables en plantillas
module.exports = async function(Odac) {
const user = await Odac.Auth.user()
// Email template
const template = `
Hello {{name}},
Your account {{email}} has been verified.
You can now access your dashboard at {{url}}.
Thanks,
{{site}}
`
// Replace variables
const emailContent = Odac.Var(template).replace({
'{{name}}': user.name,
'{{email}}': user.email,
'{{url}}': 'https://example.com/dashboard',
'{{site}}': 'Odac'
})
// Send email
await Odac.Mail.send({
to: user.email,
subject: 'Account Verified',
body: emailContent
})
return Odac.return({success: true})
}
Formato de números de teléfono
module.exports = async function(Odac) {
const phone = Odac.Request.post('phone')
// Remove all non-numeric characters
const cleanPhone = Odac.Var(phone).clear('-', ' ', '(', ')', '+')
// Validate it's numeric
if (!Odac.Var(cleanPhone).is('numeric')) {
return Odac.return({
success: false,
message: 'Invalid phone number'
})
}
// Format for display
const formattedPhone = Odac.Var(cleanPhone).format('(???) ???-????')
return Odac.return({
success: true,
phone: formattedPhone
})
}
Cifrado de datos para almacenamiento
module.exports = async function(Odac) {
const creditCard = Odac.Request.post('credit_card')
// Encrypt sensitive data
const encryptedCard = Odac.Var(creditCard).encrypt()
// Save encrypted data
await Odac.DB.payments.insert({
user_id: Odac.Auth.id(),
card: encryptedCard
})
return Odac.return({success: true})
}
// Later, to retrieve and decrypt
module.exports = async function(Odac) {
const payment = await Odac.DB.payments
.where('user_id', Odac.Auth.id())
.first()
// Decrypt data
const creditCard = Odac.Var(payment.card).decrypt()
return Odac.return({
card: creditCard
})
}
Buenas prácticas
- Valida siempre la entrada del usuario antes de procesarla
- Usa hash() para las contraseñas, nunca las guardes en texto plano
- Usa encrypt() para datos sensibles como tarjetas de crédito o números SSN
- Crea slugs para las URL para que sean amigables para SEO
- Sanitiza el HTML con html() para prevenir ataques XSS
- Usa isBegin/isEnd para comprobar protocolos o extensiones de archivo
Notas
- El cifrado utiliza AES-256-GCM con un IV aleatorio por llamada; un texto cifrado manipulado o con una clave incorrecta hace que
decrypt()devuelvanull. Los valores cifrados con versiones anteriores (AES-256-CBC) siguen descifrándose. - En producción (
NODE_ENV=production),encrypt()/decrypt()lanzan una excepción mientrasencrypt.keyenodac.jsonconserve el valor predeterminado. - El hashing con scrypt es unidireccional y computacionalmente costoso para evitar ataques de fuerza bruta.
- El formato de fechas funciona con cualquier cadena de fecha válida de JavaScript