has()
title: has description: Verifica se uma chave existe no banco de dados
Section titled “title: has description: Verifica se uma chave existe no banco de dados”has() - Verificar Existência
Section titled “has() - Verificar Existência”O método has() verifica se uma chave existe no banco de dados, retornando true ou false.
Sintaxe
Section titled “Sintaxe”await db.has(key)Parâmetros
Section titled “Parâmetros”- key (
string): A chave a ser verificada
Retorno
Section titled “Retorno”- boolean:
truese a chave existe,falsecaso contrário
Exemplos
Section titled “Exemplos”Verificação Básica
Section titled “Verificação Básica”const { HelperDB } = require('helper.db');const db = new HelperDB();
// Definir dadosawait db.set('user:1', { name: 'João' });
// Verificar existênciaconst exists = await db.has('user:1');console.log(exists); // true
const notExists = await db.has('user:999');console.log(notExists); // falseVerificação Condicional
Section titled “Verificação Condicional”// Verificar antes de acessarif (await db.has('config:theme')) { const theme = await db.get('config:theme'); console.log('Tema atual:', theme);} else { console.log('Tema não configurado');}Verificação em Lote
Section titled “Verificação em Lote”const keys = ['user:1', 'user:2', 'user:3'];const results = {};
for (const key of keys) { results[key] = await db.has(key);}
console.log(results);// { 'user:1': true, 'user:2': false, 'user:3': true }Validação de Dados
Section titled “Validação de Dados”async function updateUser(userId, data) { const userKey = `user:${userId}`;
if (!(await db.has(userKey))) { throw new Error('Usuário não encontrado'); }
// Prosseguir com atualização await db.set(userKey, data);}Casos de Uso
Section titled “Casos de Uso”🔍 Validação de Entrada
Section titled “🔍 Validação de Entrada”async function deleteUser(userId) { if (!(await db.has(`user:${userId}`))) { return { error: 'Usuário não encontrado' }; }
await db.delete(`user:${userId}`); return { success: true };}📊 Estatísticas
Section titled “📊 Estatísticas”async function getUserStats() { const totalUsers = await db.count('user:*'); const activeUsers = 0;
for (let i = 1; i <= totalUsers; i++) { if (await db.has(`user:${i}`)) { const user = await db.get(`user:${i}`); if (user.status === 'active') activeUsers++; } }
return { total: totalUsers, active: activeUsers };}🔄 Cache Inteligente
Section titled “🔄 Cache Inteligente”async function getCachedData(key) { const cacheKey = `cache:${key}`;
if (await db.has(cacheKey)) { return await db.get(cacheKey); }
// Buscar dados da fonte const data = await fetchFromAPI(key); await db.set(cacheKey, data);
return data;}Performance
Section titled “Performance”- Complexidade: O(1) - Tempo constante
- Uso de memória: Mínimo
- Ideal para: Validações rápidas e verificações condicionais
- Não gera erro se a chave não existir
- Funciona com qualquer tipo de chave válida
- Operação muito rápida em todos os drivers
- Útil para evitar erros em operações subsequentes