database package

Banco de dados em tempo real do Firebase

Funções

Função Descrição
função(aplicativo...)
getDatabase(aplicativo, url) Retorna a instância do Realtime Database SDK associada ao FirebaseApp fornecido . Inicializa uma nova instância com configurações padrão se nenhuma instância existir ou se a instância existente usar uma URL de banco de dados personalizada.
função(db...)
connectDatabaseEmulator(db, host, porta, opções) Modifique a instância fornecida para se comunicar com o emulador do Realtime Database.

Nota: Este método deve ser chamado antes de executar qualquer outra operação.

goOffline(db) Desconecta do servidor (todas as operações do banco de dados serão concluídas offline). O cliente mantém automaticamente uma conexão persistente com o servidor de Banco de Dados, que permanecerá ativo indefinidamente e reconectará quando desconectado. No entanto, os métodos goOffline() e goOnline() podem ser usados ​​para controlar a conexão do cliente nos casos em que uma conexão persistente é indesejável. Enquanto estiver offline, o cliente não receberá mais atualizações de dados do Banco de Dados. No entanto, todas as operações de Banco de Dados executadas localmente continuarão a disparar eventos imediatamente, permitindo que seu aplicativo continue se comportando normalmente. Além disso, cada operação executada localmente será automaticamente enfileirada e repetida na reconexão ao servidor de banco de dados. Para reconectar ao Banco de Dados e começar a receber eventos remotos, consulte goOnline() .
goOnline(db) Reconecta ao servidor e sincroniza o estado offline do banco de dados com o estado do servidor. Este método deve ser usado após desabilitar a conexão ativa com goOffline() . Uma vez reconectado, o cliente transmitirá os dados apropriados e disparará os eventos apropriados para que seu cliente "se atualize" automaticamente.
ref(db, caminho) Retorna uma Reference que representa a localização no Banco de Dados correspondente ao caminho fornecido. Se nenhum caminho for fornecido, a Reference apontará para a raiz do Banco de Dados.
refFromURL(db, url) Retorna uma Reference que representa o local no banco de dados correspondente ao URL do Firebase fornecido. Uma exceção é lançada se o URL não for um URL válido do Firebase Database ou se tiver um domínio diferente da instância atual Database . Observe que todos os parâmetros de consulta ( orderBy , limitToLast , etc.) são ignorados e não são aplicados ao Reference retornado .
função()
forceLongPolling() Forçar o uso de longPolling em vez de websockets. Isso será ignorado se o protocolo websocket for usado em databaseURL.
forceWebSockets() Força o uso de websockets em vez de longPolling.
orderByKey() Cria um novo QueryConstraint que ordena pela chave. Classifica os resultados de uma consulta por seus valores de chave (crescente). Você pode ler mais sobre orderByKey() em Classificar dados .
orderByPriority() Cria um novo QueryConstraint que ordena por prioridade. Os aplicativos não precisam usar prioridade, mas podem ordenar coleções por propriedades comuns (consulte Classificar dados para alternativas à prioridade.
pedidoPorValor() Cria um novo QueryConstraint que ordena por valor. Se os filhos de uma consulta forem todos valores escalares (string, número ou booleano), você poderá ordenar os resultados por seus valores (crescentes). Você pode ler mais sobre orderByValue() em Classificar dados .
serverTimestamp() Retorna um valor de espaço reservado para preencher automaticamente o carimbo de data/hora atual (tempo desde a época do Unix, em milissegundos), conforme determinado pelos servidores Firebase.
function(delta...)
incremento(delta) Retorna um valor de espaço reservado que pode ser usado para incrementar atomicamente o valor do banco de dados atual pelo delta fornecido.
função(habilitada...)
enableLogging(ativado, persistente) Registra informações de depuração no console.
função(limite...)
limitToFirst(limite) Cria um novo QueryConstraint que se limita ao primeiro número específico de filhos. O método limitToFirst() é usado para definir um número máximo de filhos a serem sincronizados para um determinado retorno de chamada. Se definirmos um limite de 100, inicialmente receberemos apenas até 100 eventos child_added . Se tivermos menos de 100 mensagens armazenadas em nosso banco de dados, um evento child_added será acionado para cada mensagem. No entanto, se tivermos mais de 100 mensagens, receberemos um evento child_added apenas para as primeiras 100 mensagens solicitadas. À medida que os itens forem alterados, receberemos eventos child_removed para cada item que sair da lista ativa para que o número total permaneça em 100. Você pode ler mais sobre limitToFirst() em Filtrando dados .
limitToLast(limite) Cria um novo QueryConstraint limitado a retornar apenas o último número especificado de filhos. O método limitToLast() é usado para definir um número máximo de filhos a serem sincronizados para um determinado retorno de chamada. Se definirmos um limite de 100, inicialmente receberemos apenas até 100 eventos child_added . Se tivermos menos de 100 mensagens armazenadas em nosso banco de dados, um evento child_added será acionado para cada mensagem. No entanto, se tivermos mais de 100 mensagens, receberemos um evento child_added apenas para as últimas 100 mensagens solicitadas. À medida que os itens forem alterados, receberemos eventos child_removed para cada item que sair da lista ativa para que o número total permaneça em 100. Você pode ler mais sobre limitToLast() em Filtrando dados .
função (logger...)
enableLogging(logger) Registra informações de depuração no console.
function(pai...)
filho(pai, caminho) Obtém uma Reference para o local no caminho relativo especificado. O caminho relativo pode ser um nome filho simples (por exemplo, "ada") ou um caminho mais profundo separado por barra (por exemplo, "ada/nome/primeiro").
push(pai, valor) Gera um novo local filho usando uma chave exclusiva e retorna sua Reference . Este é o padrão mais comum para adicionar dados a uma coleção de itens. Se você fornecer um valor para push() , o valor será gravado no local gerado. Se você não passar um valor, nada é gravado no banco de dados e o filho permanece vazio (mas você pode usar a Reference em outro lugar). As chaves exclusivas geradas por push() são ordenadas pela hora atual, portanto, a lista de itens resultante é classificada cronologicamente. As chaves também são projetadas para serem indecifráveis ​​(contêm 72 bits aleatórios de entropia). Consulte Anexar a uma lista de dados . Veja as 2 ^ 120 maneiras de garantir identificadores exclusivos .
função(caminho...)
orderByChild(caminho) Cria um novo QueryConstraint que ordena pela chave filha especificada. As consultas só podem ser ordenadas por uma chave por vez. Chamar orderByChild() várias vezes na mesma consulta é um erro. As consultas do Firebase permitem que você ordene seus dados por qualquer chave filha em tempo real. No entanto, se você souber antecipadamente quais serão seus índices, poderá defini-los por meio da regra .indexOn em suas Regras de segurança para obter melhor desempenho. Consulte a regra https://firebase.google.com/docs/database/security/indexing-data para obter mais informações. Você pode ler mais sobre orderByChild() em Sort data .
function(consulta...)
obter (consulta) Obtém o resultado mais atualizado para esta consulta.
off(consulta, eventType, retorno de chamada) Desanexa um retorno de chamada anexado anteriormente com o ouvinte on () ( onValue , onChildAdded ) correspondente. Observação: essa não é a maneira recomendada de remover um ouvinte. Em vez disso, use a função de retorno de chamada retornada dos respectivos retornos on chamada. Desanexar um callback previamente anexado com on*() . Chamar off() em um ouvinte pai não removerá automaticamente os ouvintes registrados em nós filhos, off() também deve ser chamado em qualquer ouvinte filho para remover o retorno de chamada. Se um retorno de chamada não for especificado, todos os retornos de chamada para o eventType especificado serão removidos. Da mesma forma, se nenhum eventType for especificado, todos os retornos de chamada para a Reference serão removidos. Os ouvintes individuais também podem ser removidos invocando seus retornos de chamada de cancelamento de inscrição.
onChildAdded(consulta, callback, cancelCallback) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildAdded será acionado uma vez para cada filho inicial neste local e será acionado novamente sempre que um novo filho for adicionado. O DataSnapshot passado para o retorno de chamada refletirá os dados do filho relevante. Para fins de ordenação, é passado um segundo argumento que é uma string contendo a chave do filho irmão anterior por ordem de classificação, ou null se for o primeiro filho.
onChildAdded(consulta, retorno de chamada, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildAdded será acionado uma vez para cada filho inicial neste local e será acionado novamente sempre que um novo filho for adicionado. O DataSnapshot passado para o retorno de chamada refletirá os dados do filho relevante. Para fins de ordenação, é passado um segundo argumento que é uma string contendo a chave do filho irmão anterior por ordem de classificação, ou null se for o primeiro filho.
onChildAdded(consulta, callback, cancelCallback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildAdded será acionado uma vez para cada filho inicial neste local e será acionado novamente sempre que um novo filho for adicionado. O DataSnapshot passado para o retorno de chamada refletirá os dados do filho relevante. Para fins de ordenação, é passado um segundo argumento que é uma string contendo a chave do filho irmão anterior por ordem de classificação, ou null se for o primeiro filho.
onChildChanged(consulta, callback, cancelCallback) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildChanged será acionado quando os dados armazenados em um filho (ou qualquer um de seus descendentes) forem alterados. Observe que um único evento child_changed pode representar várias alterações no filho. O DataSnapshot passado para o retorno de chamada conterá o novo conteúdo filho. Para fins de ordenação, o retorno de chamada também recebe um segundo argumento, que é uma string contendo a chave do filho irmão anterior por ordem de classificação ou null se for o primeiro filho.
onChildChanged(consulta, callback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildChanged será acionado quando os dados armazenados em um filho (ou qualquer um de seus descendentes) forem alterados. Observe que um único evento child_changed pode representar várias alterações no filho. O DataSnapshot passado para o retorno de chamada conterá o novo conteúdo filho. Para fins de ordenação, o retorno de chamada também recebe um segundo argumento, que é uma string contendo a chave do filho irmão anterior por ordem de classificação ou null se for o primeiro filho.
onChildChanged(consulta, callback, cancelCallback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildChanged será acionado quando os dados armazenados em um filho (ou qualquer um de seus descendentes) forem alterados. Observe que um único evento child_changed pode representar várias alterações no filho. O DataSnapshot passado para o retorno de chamada conterá o novo conteúdo filho. Para fins de ordenação, o retorno de chamada também recebe um segundo argumento, que é uma string contendo a chave do filho irmão anterior por ordem de classificação ou null se for o primeiro filho.
onChildMoved(consulta, callback, cancelCallback) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildMoved será acionado quando a ordem de classificação de um filho mudar de forma que sua posição em relação a seus irmãos mude. O DataSnapshot passado para o callback será para os dados do filho que foi movido. Também é passado um segundo argumento que é uma string contendo a chave do filho irmão anterior por ordem de classificação, ou null se for o primeiro filho.
onChildMoved(consulta, callback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildMoved será acionado quando a ordem de classificação de um filho mudar de forma que sua posição em relação a seus irmãos mude. O DataSnapshot passado para o callback será para os dados do filho que foi movido. Também é passado um segundo argumento que é uma string contendo a chave do filho irmão anterior por ordem de classificação, ou null se for o primeiro filho.
onChildMoved(consulta, callback, cancelCallback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildMoved será acionado quando a ordem de classificação de um filho mudar de forma que sua posição em relação a seus irmãos mude. O DataSnapshot passado para o callback será para os dados do filho que foi movido. Também é passado um segundo argumento que é uma string contendo a chave do filho irmão anterior por ordem de classificação, ou null se for o primeiro filho.
onChildRemoved(consulta, callback, cancelCallback) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildRemoved será acionado sempre que um filho for removido. O DataSnapshot passado para o retorno de chamada será os dados antigos do filho que foi removido. Uma criança será removida quando: - um cliente chama explicitamente remove() nesse filho ou em um de seus ancestrais - um cliente chama set(null) nesse filho ou em um de seus ancestrais - esse filho tem todos os seus filhos removidos - há uma consulta em vigor que agora filtra o filho (porque a ordem de classificação foi alterada ou o limite máximo foi atingido)
onChildRemoved(consulta, callback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildRemoved será acionado sempre que um filho for removido. O DataSnapshot passado para o retorno de chamada será os dados antigos do filho que foi removido. Uma criança será removida quando: - um cliente chama explicitamente remove() nesse filho ou em um de seus ancestrais - um cliente chama set(null) nesse filho ou em um de seus ancestrais - esse filho tem todos os seus filhos removidos - há uma consulta em vigor que agora filtra o filho (porque a ordem de classificação foi alterada ou o limite máximo foi atingido)
onChildRemoved(consulta, callback, cancelCallback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onChildRemoved será acionado sempre que um filho for removido. O DataSnapshot passado para o retorno de chamada será os dados antigos do filho que foi removido. Uma criança será removida quando: - um cliente chama explicitamente remove() nesse filho ou em um de seus ancestrais - um cliente chama set(null) nesse filho ou em um de seus ancestrais - esse filho tem todos os seus filhos removidos - há uma consulta em vigor que agora filtra o filho (porque a ordem de classificação foi alterada ou o limite máximo foi atingido)
onValue(consulta, callback, cancelCallback) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onValue será acionado uma vez com os dados iniciais armazenados neste local e, em seguida, acionado novamente sempre que os dados forem alterados. O DataSnapshot passado para o retorno de chamada será para o local em que on() foi chamado. Ele não será acionado até que todo o conteúdo tenha sido sincronizado. Se o local não tiver dados, ele será acionado com um DataSnapshot vazio ( val() retornará null ).
onValue(consulta, callback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onValue será acionado uma vez com os dados iniciais armazenados neste local e, em seguida, acionado novamente sempre que os dados forem alterados. O DataSnapshot passado para o retorno de chamada será para o local em que on() foi chamado. Ele não será acionado até que todo o conteúdo tenha sido sincronizado. Se o local não tiver dados, ele será acionado com um DataSnapshot vazio ( val() retornará null ).
onValue(consulta, callback, cancelCallback, opções) Escuta as alterações de dados em um determinado local. Esta é a principal maneira de ler dados de um banco de dados. Seu retorno de chamada será acionado para os dados iniciais e novamente sempre que os dados forem alterados. Invoque o retorno de chamada de cancelamento de inscrição retornado para parar de receber atualizações. Consulte Recuperar dados na Web para obter mais detalhes. Um evento onValue será acionado uma vez com os dados iniciais armazenados neste local e, em seguida, acionado novamente sempre que os dados forem alterados. O DataSnapshot passado para o retorno de chamada será para o local em que on() foi chamado. Ele não será acionado até que todo o conteúdo tenha sido sincronizado. Se o local não tiver dados, ele será acionado com um DataSnapshot vazio ( val() retornará null ).
query(consulta, queryConstraints) Cria uma nova instância imutável de Query que é estendida para incluir também restrições de consulta adicionais.
função(ref...)
onDisconnect (ref) Retorna um objeto OnDisconnect - consulte Ativando recursos offline em JavaScript para obter mais informações sobre como usá-lo.
remover(ref) Remove os dados neste local do banco de dados. Todos os dados em locais filhos também serão excluídos. O efeito da remoção ficará visível imediatamente e o 'valor' do evento correspondente será acionado. A sincronização da remoção com os servidores Firebase também será iniciada e a promessa retornada será resolvida quando concluída. Se fornecido, o retorno de chamada onComplete será chamado de forma assíncrona após o término da sincronização.
runTransaction(ref, transactionUpdate, opções) Modifica atomicamente os dados neste local. Modifique atomicamente os dados neste local. Ao contrário de um set() normal, que apenas sobrescreve os dados independentemente de seu valor anterior, runTransaction() é usado para modificar o valor existente para um novo valor, garantindo que não haja conflitos com outros clientes gravando no mesmo local ao mesmo tempo . Para conseguir isso, você passa runTransaction() uma função de atualização que é usada para transformar o valor atual em um novo valor. Se outro cliente gravar no local antes de seu novo valor ser gravado com sucesso, sua função de atualização será chamada novamente com o novo valor atual e a gravação será repetida. Isso acontecerá repetidamente até que sua gravação seja bem-sucedida sem conflito ou você aborte a transação por não retornar um valor de sua função de atualização. Observação: a modificação de dados com set() cancelará todas as transações pendentes naquele local, portanto, deve-se tomar muito cuidado ao misturar set() e runTransaction() para atualizar os mesmos dados. Observação: ao usar transações com regras de segurança e Firebase em vigor, lembre-se de que um cliente precisa de acesso .read além do acesso .write para realizar uma transação. Isso ocorre porque a natureza das transações do lado do cliente exige que o cliente leia os dados para atualizá-los transacionalmente.
set(ref, valor) Grava dados neste local do banco de dados. Isso substituirá todos os dados neste local e em todos os locais filhos. O efeito da gravação será visível imediatamente e os eventos correspondentes ("value", "child_added", etc.) serão acionados. A sincronização dos dados com os servidores Firebase também será iniciada e a promessa retornada será resolvida quando concluída. Se fornecido, o retorno de chamada onComplete será chamado de forma assíncrona após o término da sincronização. Passar null para o novo valor é equivalente a chamar remove() ; ou seja, todos os dados neste local e todos os locais filho serão excluídos. set() removerá qualquer prioridade armazenada neste local, portanto, se a prioridade for preservada, você precisará usar setWithPriority() . Observe que a modificação de dados com set() cancelará todas as transações pendentes naquele local, portanto, deve-se tomar muito cuidado ao misturar set() e transaction() para modificar os mesmos dados. Um único set() irá gerar um único evento de "valor" no local onde o set() foi executado.
setPriority(ref, prioridade) Define uma prioridade para os dados neste local do banco de dados. Os aplicativos não precisam usar prioridade, mas podem ordenar coleções por propriedades comuns (consulte Classificando e filtrando dados ).
setWithPriority(ref, valor, prioridade) Grava dados no local do banco de dados. Como set() , mas também especifica a prioridade para esses dados. Os aplicativos não precisam usar prioridade, mas podem ordenar coleções por propriedades comuns (consulte Classificando e filtrando dados ).
atualizar(ref, valores) Grava vários valores no banco de dados de uma só vez. O argumento values ​​contém vários pares propriedade-valor que serão gravados juntos no banco de dados. Cada propriedade filho pode ser uma propriedade simples (por exemplo, "nome") ou um caminho relativo (por exemplo, "nome/primeiro") do local atual para os dados a serem atualizados. Ao contrário do método set() , update() pode ser usado para atualizar seletivamente apenas as propriedades referenciadas no local atual (em vez de substituir todas as propriedades filhas no local atual). O efeito da gravação será visível imediatamente e os eventos correspondentes ('value', 'child_added', etc.) serão acionados. A sincronização dos dados com os servidores Firebase também será iniciada e a promessa retornada será resolvida quando concluída. Se fornecido, o retorno de chamada onComplete será chamado de forma assíncrona após o término da sincronização. Um único update() irá gerar um único evento "value" no local onde o update() foi executado, independentemente de quantos filhos foram modificados. Observe que a modificação de dados com update() cancelará todas as transações pendentes naquele local, portanto, deve-se tomar extremo cuidado ao misturar update() e transaction() para modificar os mesmos dados. Passar null para update() removerá os dados neste local. Consulte Apresentando atualizações de vários locais e muito mais .
função(valor...)
endAt(valor, chave) Cria um QueryConstraint com o ponto final especificado. Usar startAt() , startAfter() , endBefore() , endAt() e equalTo() permite que você escolha pontos iniciais e finais arbitrários para suas consultas. O ponto final é inclusivo, portanto, filhos com exatamente o valor especificado serão incluídos na consulta. O argumento de chave opcional pode ser usado para limitar ainda mais o intervalo da consulta. Se for especificado, os filhos que tiverem exatamente o valor especificado também deverão ter um nome de chave menor ou igual à chave especificada. Você pode ler mais sobre endAt() em Filtrando dados .
endBefore(valor, chave) Cria um QueryConstraint com o ponto final especificado (exclusivo). Usar startAt() , startAfter() , endBefore() , endAt() e equalTo() permite que você escolha pontos iniciais e finais arbitrários para suas consultas. O ponto final é exclusivo. Se apenas um valor for fornecido, os filhos com um valor menor que o valor especificado serão incluídos na consulta. Se uma chave for especificada, os filhos deverão ter um valor menor ou igual ao valor especificado e um nome de chave menor que a chave especificada.
equalTo(valor, chave) Cria um QueryConstraint que inclui filhos que correspondem ao valor especificado. Usar startAt() , startAfter() , endBefore() , endAt() e equalTo() permite que você escolha pontos iniciais e finais arbitrários para suas consultas. O argumento de chave opcional pode ser usado para limitar ainda mais o intervalo da consulta. Se for especificado, os filhos que tiverem exatamente o valor especificado também deverão ter exatamente a chave especificada como seu nome de chave. Isso pode ser usado para filtrar conjuntos de resultados com muitas correspondências para o mesmo valor. Você pode ler mais sobre equalTo() em Filtrando dados .
startAfter(valor, chave) Cria um QueryConstraint com o ponto inicial especificado (exclusivo). Usar startAt() , startAfter() , endBefore() , endAt() e equalTo() permite que você escolha pontos iniciais e finais arbitrários para suas consultas. O ponto de partida é exclusivo. Se apenas um valor for fornecido, os filhos com um valor maior que o valor especificado serão incluídos na consulta. Se uma chave for especificada, os filhos deverão ter um valor maior ou igual ao valor especificado e um nome de chave maior que a chave especificada.
startAt(valor, chave) Cria um QueryConstraint com o ponto inicial especificado. Usar startAt() , startAfter() , endBefore() , endAt() e equalTo() permite que você escolha pontos iniciais e finais arbitrários para suas consultas. O ponto de partida é inclusivo, portanto, filhos com exatamente o valor especificado serão incluídos na consulta. O argumento de chave opcional pode ser usado para limitar ainda mais o intervalo da consulta. Se for especificado, os filhos que tiverem exatamente o valor especificado também deverão ter um nome de chave maior ou igual à chave especificada. Você pode ler mais sobre startAt() em Filtrando dados .

Aulas

Aula Descrição
Base de dados Classe que representa um Firebase Realtime Database.
DataSnapshot Um DataSnapshot contém dados de um local de banco de dados. Sempre que você lê dados do banco de dados, você recebe os dados como um DataSnapshot . Um DataSnapshot é passado para os retornos de chamada de evento que você anexa com on() ou once() . Você pode extrair o conteúdo do instantâneo como um objeto JavaScript chamando o método val() . Como alternativa, você pode percorrer o instantâneo chamando child() para retornar instantâneos filhos (nos quais você pode chamar val() ). Um DataSnapshot é uma cópia imutável e gerada com eficiência dos dados em um local do banco de dados. Ele não pode ser modificado e nunca mudará (para modificar dados, você sempre chama o método set() em uma Reference diretamente).
OnDisconnect A classe onDisconnect permite gravar ou limpar dados quando seu cliente se desconecta do servidor de banco de dados. Essas atualizações ocorrem independentemente de seu cliente se desconectar corretamente ou não, portanto, você pode confiar nelas para limpar os dados mesmo se uma conexão cair ou um cliente travar. A classe onDisconnect é mais comumente usada para gerenciar a presença em aplicativos nos quais é útil detectar quantos clientes estão conectados e quando outros clientes se desconectam. Consulte Habilitando recursos offline em JavaScript para obter mais informações. Para evitar problemas quando uma conexão cai antes que as requisições possam ser transferidas para o servidor de Banco de Dados, estas funções devem ser chamadas antes de escrever qualquer dado. Observe que as operações onDisconnect são acionadas apenas uma vez. Se você quiser que uma operação ocorra sempre que ocorrer uma desconexão, será necessário restabelecer as operações onDisconnect sempre que você se reconectar.
QueryConstraint Um QueryConstraint é usado para restringir o conjunto de documentos retornados por uma consulta de banco de dados. QueryConstraint s são criados invocando endAt() , fimAntes() , startAt() , comeceDepois() , limitToFirst() , limitToLast() , ordemPorCriança() , ordemPorCriança() , orderByKey() , orderByPriority() , orderByValue() ou equalTo() e podem ser passados ​​para query() para criar uma nova instância de consulta que também contém esse QueryConstraint .
Resultado da Transação Um tipo para o valor de resolução de runTransaction() .

Interfaces

Interface Descrição
Referência do banco de dados Um DatabaseReference representa um local específico em seu banco de dados e pode ser usado para ler ou gravar dados nesse local do banco de dados. Você pode fazer referência ao local raiz ou filho em seu banco de dados chamando ref() ou ref("child/path") . A escrita é feita com o método set() e a leitura pode ser feita com o método on*() . Consulte https://firebase.google.com/docs/database/web/read-and-write
IteratedDataSnapshot Representa um instantâneo filho de uma Reference que está sendo iterada. A chave nunca será indefinida.
Opções de escuta Um objeto de opções que pode ser usado para personalizar um ouvinte.
Consulta Uma Query classifica e filtra os dados em um local do banco de dados para que apenas um subconjunto dos dados filhos seja incluído. Isso pode ser usado para ordenar uma coleção de dados por algum atributo (por exemplo, altura dos dinossauros), bem como para restringir uma grande lista de itens (por exemplo, mensagens de bate-papo) a um número adequado para sincronização com o cliente. As consultas são criadas encadeando um ou mais dos métodos de filtro definidos aqui. Assim como com um DatabaseReference , você pode receber dados de uma Query usando os métodos on*() . Você só receberá eventos e DataSnapshot s para o subconjunto de dados que correspondem à sua consulta. Consulte https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data para obter mais informações.
ThenableReference Um Promise que também pode atuar como um DatabaseReference quando retornado por push() . A referência está disponível imediatamente e a Promise é resolvida conforme a gravação no back-end é concluída.
Opções de Transação Um objeto de opções para configurar transações.

Aliases de tipo

Digite Alias Descrição
Tipo de evento Uma das seguintes strings: "value", "child_added", "child_changed", "child_removed" ou "child_moved".
QueryConstraintType Descreve as diferentes restrições de consulta disponíveis neste SDK.
Cancelar subscrição A callback that can invoked to remove a listener.

getDatabase()

Returns the instance of the Realtime Database SDK that is associated with the provided FirebaseApp . Initializes a new instance with with default settings if no instance exists or if the existing instance uses a custom database URL.

Assinatura:

export declare function getDatabase(app?: FirebaseApp, url?: string): Database;

Parâmetros

Parâmetro Tipo Descrição
app FirebaseApp The FirebaseApp instance that the returned Realtime Database instance is associated with.
url corda The URL of the Realtime Database instance to connect to. If not provided, the SDK connects to the default instance of the Firebase App.

Retorna:

Database

The Database instance of the provided app.

connectDatabaseEmulator()

Modify the provided instance to communicate with the Realtime Database emulator.

Note: This method must be called before performing any other operation.

Assinatura:

export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: {
    mockUserToken?: EmulatorMockTokenOptions | string;
}): void;

Parâmetros

Parâmetro Tipo Descrição
db Database The instance to modify.
host corda The emulator host (ex: localhost)
port número The emulator port (ex: 8080)
opções { mockUserToken?: EmulatorMockTokenOptions | string; }

Retorna:

vazio

goOffline()

Disconnects from the server (all Database operations will be completed offline).

The client automatically maintains a persistent connection to the Database server, which will remain active indefinitely and reconnect when disconnected. However, the goOffline() and goOnline() methods may be used to control the client connection in cases where a persistent connection is undesirable.

While offline, the client will no longer receive data updates from the Database. However, all Database operations performed locally will continue to immediately fire events, allowing your application to continue behaving normally. Additionally, each operation performed locally will automatically be queued and retried upon reconnection to the Database server.

To reconnect to the Database and begin receiving remote events, see goOnline() .

Assinatura:

export declare function goOffline(db: Database): void;

Parâmetros

Parâmetro Tipo Descrição
db Database The instance to disconnect.

Retorna:

vazio

goOnline()

Reconnects to the server and synchronizes the offline Database state with the server state.

This method should be used after disabling the active connection with goOffline() . Once reconnected, the client will transmit the proper data and fire the appropriate events so that your client "catches up" automatically.

Assinatura:

export declare function goOnline(db: Database): void;

Parâmetros

Parâmetro Tipo Descrição
db Database The instance to reconnect.

Retorna:

vazio

ref()

Returns a Reference representing the location in the Database corresponding to the provided path. If no path is provided, the Reference will point to the root of the Database.

Assinatura:

export declare function ref(db: Database, path?: string): DatabaseReference;

Parâmetros

Parâmetro Tipo Descrição
db Database The database instance to obtain a reference for.
path corda Optional path representing the location the returned Reference will point. If not provided, the returned Reference will point to the root of the Database.

Retorna:

DatabaseReference

If a path is provided, a Reference pointing to the provided path. Otherwise, a Reference pointing to the root of the Database.

refFromURL()

Returns a Reference representing the location in the Database corresponding to the provided Firebase URL.

An exception is thrown if the URL is not a valid Firebase Database URL or it has a different domain than the current Database instance.

Note that all query parameters ( orderBy , limitToLast , etc.) are ignored and are not applied to the returned Reference .

Assinatura:

export declare function refFromURL(db: Database, url: string): DatabaseReference;

Parâmetros

Parâmetro Tipo Descrição
db Database The database instance to obtain a reference for.
url corda The Firebase URL at which the returned Reference will point.

Retorna:

DatabaseReference

A Reference pointing to the provided Firebase URL.

forceLongPolling()

Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.

Assinatura:

export declare function forceLongPolling(): void;

Retorna:

vazio

forceWebSockets()

Force the use of websockets instead of longPolling.

Assinatura:

export declare function forceWebSockets(): void;

Retorna:

vazio

orderByKey()

Creates a new QueryConstraint that orders by the key.

Sorts the results of a query by their (ascending) key values.

You can read more about orderByKey() in Sort data .

Assinatura:

export declare function orderByKey(): QueryConstraint;

Retorna:

QueryConstraint

orderByPriority()

Creates a new QueryConstraint that orders by priority.

Applications need not use priority but can order collections by ordinary properties (see Sort data for alternatives to priority.

Assinatura:

export declare function orderByPriority(): QueryConstraint;

Retorna:

QueryConstraint

orderByValue()

Creates a new QueryConstraint that orders by value.

If the children of a query are all scalar values (string, number, or boolean), you can order the results by their (ascending) values.

You can read more about orderByValue() in Sort data .

Assinatura:

export declare function orderByValue(): QueryConstraint;

Retorna:

QueryConstraint

serverTimestamp()

Returns a placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers.

Assinatura:

export declare function serverTimestamp(): object;

Retorna:

object

increment()

Returns a placeholder value that can be used to atomically increment the current database value by the provided delta.

Assinatura:

export declare function increment(delta: number): object;

Parâmetros

Parâmetro Tipo Descrição
delta número the amount to modify the current value atomically.

Retorna:

object

A placeholder value for modifying data atomically server-side.

enableLogging()

Logs debugging information to the console.

Assinatura:

export declare function enableLogging(enabled: boolean, persistent?: boolean): any;

Parâmetros

Parâmetro Tipo Descrição
enabled boleano Enables logging if true , disables logging if false .
persistent boleano Remembers the logging state between page refreshes if true .

Retorna:

qualquer

limitToFirst()

Creates a new QueryConstraint that if limited to the first specific number of children.

The limitToFirst() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100 child_added events. If we have fewer than 100 messages stored in our Database, a child_added event will fire for each message. However, if we have over 100 messages, we will only receive a child_added event for the first 100 ordered messages. As items change, we will receive child_removed events for each item that drops out of the active list so that the total number stays at 100.

You can read more about limitToFirst() in Filtering data .

Assinatura:

export declare function limitToFirst(limit: number): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
limit número The maximum number of nodes to include in this query.

Retorna:

QueryConstraint

limitToLast()

Creates a new QueryConstraint that is limited to return only the last specified number of children.

The limitToLast() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100 child_added events. If we have fewer than 100 messages stored in our Database, a child_added event will fire for each message. However, if we have over 100 messages, we will only receive a child_added event for the last 100 ordered messages. As items change, we will receive child_removed events for each item that drops out of the active list so that the total number stays at 100.

You can read more about limitToLast() in Filtering data .

Assinatura:

export declare function limitToLast(limit: number): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
limit número The maximum number of nodes to include in this query.

Retorna:

QueryConstraint

enableLogging()

Logs debugging information to the console.

Assinatura:

export declare function enableLogging(logger: (message: string) => unknown): any;

Parâmetros

Parâmetro Tipo Descrição
logger (message: string) => unknown A custom logger function to control how things get logged.

Retorna:

qualquer

child()

Gets a Reference for the location at the specified relative path.

The relative path can either be a simple child name (for example, "ada") or a deeper slash-separated path (for example, "ada/name/first").

Assinatura:

export declare function child(parent: DatabaseReference, path: string): DatabaseReference;

Parâmetros

Parâmetro Tipo Descrição
parent DatabaseReference The parent location.
path corda A relative path from this location to the desired child location.

Retorna:

DatabaseReference

The specified child location.

push()

Generates a new child location using a unique key and returns its Reference .

This is the most common pattern for adding data to a collection of items.

If you provide a value to push() , the value is written to the generated location. If you don't pass a value, nothing is written to the database and the child remains empty (but you can use the Reference elsewhere).

The unique keys generated by push() are ordered by the current time, so the resulting list of items is chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).

See Append to a list of data . See The 2^120 Ways to Ensure Unique Identifiers .

Assinatura:

export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference;

Parâmetros

Parâmetro Tipo Descrição
parent DatabaseReference The parent location.
value unknown Optional value to be written at the generated location.

Retorna:

ThenableReference

Combined Promise and Reference ; resolves when write is complete, but can be used immediately as the Reference to the child location.

orderByChild()

Creates a new QueryConstraint that orders by the specified child key.

Queries can only order by one key at a time. Calling orderByChild() multiple times on the same query is an error.

Firebase queries allow you to order your data by any child key on the fly. However, if you know in advance what your indexes will be, you can define them via the .indexOn rule in your Security Rules for better performance. See the https://firebase.google.com/docs/database/security/indexing-data rule for more information.

You can read more about orderByChild() in Sort data .

Assinatura:

export declare function orderByChild(path: string): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
path corda The path to order by.

Retorna:

QueryConstraint

get()

Gets the most up-to-date result for this query.

Assinatura:

export declare function get(query: Query): Promise<DataSnapshot>;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.

Retorna:

Promise< DataSnapshot >

A Promise which resolves to the resulting DataSnapshot if a value is available, or rejects if the client is unable to return a value (eg, if the server is unreachable and there is nothing cached).

off()

Detaches a callback previously attached with the corresponding on*() ( onValue , onChildAdded ) listener. Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from the respective on* callbacks.

Detach a callback previously attached with on*() . Calling off() on a parent listener will not automatically remove listeners registered on child nodes, off() must also be called on any child listeners to remove the callback.

If a callback is not specified, all callbacks for the specified eventType will be removed. Similarly, if no eventType is specified, all callbacks for the Reference will be removed.

Individual listeners can also be removed by invoking their unsubscribe callbacks.

Assinatura:

export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void;

Parâmetros

Parâmetro Tipo Descrição
query Query The query that the listener was registered with.
eventType EventType One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved." If omitted, all callbacks for the Reference will be removed.
callback (snapshot: DataSnapshot , previousChildName?: string | null) => unknown The callback function that was passed to on() or undefined to remove all callbacks.

Retorna:

vazio

onChildAdded()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. The DataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName?: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildAdded()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. The DataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildAdded()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. The DataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildChanged()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a single child_changed event may represent multiple changes to the child. The DataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildChanged()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a single child_changed event may represent multiple changes to the child. The DataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildChanged()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a single child_changed event may represent multiple changes to the child. The DataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildMoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. The DataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildMoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. The DataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildMoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. The DataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Assinatura:

export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildRemoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildRemoved event will be triggered once every time a child is removed. The DataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:

  • a client explicitly calls remove() on that child or one of its ancestors - a client calls set(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)

Assinatura:

export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildRemoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildRemoved event will be triggered once every time a child is removed. The DataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:

  • a client explicitly calls remove() on that child or one of its ancestors - a client calls set(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)

Assinatura:

export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onChildRemoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildRemoved event will be triggered once every time a child is removed. The DataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:

  • a client explicitly calls remove() on that child or one of its ancestors - a client calls set(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)

Assinatura:

export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onValue()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an empty DataSnapshot ( val() will return null ).

Assinatura:

export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onValue()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an empty DataSnapshot ( val() will return null ).

Assinatura:

export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

onValue()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an empty DataSnapshot ( val() will return null ).

Assinatura:

export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parâmetros

Parâmetro Tipo Descrição
query Query The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opções ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Retorna:

Unsubscribe

A function that can be invoked to remove the listener.

query()

Creates a new immutable instance of Query that is extended to also include additional query constraints.

Assinatura:

export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query;

Parâmetros

Parâmetro Tipo Descrição
query Query The Query instance to use as a base for the new constraints.
queryConstraints QueryConstraint [] The list of QueryConstraint s to apply.

Retorna:

Query

Exceptions

if any of the provided query constraints cannot be combined with the existing or new constraints.

onDisconnect()

Returns an OnDisconnect object - see Enabling Offline Capabilities in JavaScript for more information on how to use it.

Assinatura:

export declare function onDisconnect(ref: DatabaseReference): OnDisconnect;

Parâmetros

Parâmetro Tipo Descrição
ref DatabaseReference The reference to add OnDisconnect triggers for.

Retorna:

OnDisconnect

remove()

Removes the data at this Database location.

Any data at child locations will also be deleted.

The effect of the remove will be visible immediately and the corresponding event 'value' will be triggered. Synchronization of the remove to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.

Assinatura:

export declare function remove(ref: DatabaseReference): Promise<void>;

Parâmetros

Parâmetro Tipo Descrição
ref DatabaseReference The location to remove.

Retorna:

Promise<void>

Resolves when remove on server is complete.

runTransaction()

Atomically modifies the data at this location.

Atomically modify the data at this location. Unlike a normal set() , which just overwrites the data regardless of its previous value, runTransaction() is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.

To accomplish this, you pass runTransaction() an update function which is used to transform the current value into a new value. If another client writes to the location before your new value is successfully written, your update function will be called again with the new current value, and the write will be retried. This will happen repeatedly until your write succeeds without conflict or you abort the transaction by not returning a value from your update function.

Assinatura:

export declare function runTransaction(ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise<TransactionResult>;

Parâmetros

Parâmetro Tipo Descrição
ref DatabaseReference The location to atomically modify.
transactionUpdate (currentData: any) => unknown A developer-supplied function which will be passed the current data stored at this location (as a JavaScript object). The function should return the new value it would like written (as a JavaScript object). If undefined is returned (ie you return with no arguments) the transaction will be aborted and the data at this location will not be modified.
opções TransactionOptions An options object to configure transactions.

Retorna:

Promise< TransactionResult >

A Promise that can optionally be used instead of the onComplete callback to handle success and failure.

set()

Writes data to this Database location.

This will overwrite any data at this location and all child locations.

The effect of the write will be visible immediately, and the corresponding events ("value", "child_added", etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.

Passing null for the new value is equivalent to calling remove() ; namely, all data at this location and all child locations will be deleted.

set() will remove any priority stored at this location, so if priority is meant to be preserved, you need to use setWithPriority() instead.

Note that modifying data with set() will cancel any pending transactions at that location, so extreme care should be taken if mixing set() and transaction() to modify the same data.

A single set() will generate a single "value" event at the location where the set() was performed.

Assinatura:

export declare function set(ref: DatabaseReference, value: unknown): Promise<void>;

Parâmetros

Parâmetro Tipo Descrição
ref DatabaseReference The location to write to.
value unknown The value to be written (string, number, boolean, object, array, or null).

Retorna:

Promise<void>

Resolves when write to server is complete.

setPriority()

Sets a priority for the data at this Database location.

Applications need not use priority but can order collections by ordinary properties (see Sorting and filtering data ).

Assinatura:

export declare function setPriority(ref: DatabaseReference, priority: string | number | null): Promise<void>;

Parâmetros

Parâmetro Tipo Descrição
ref DatabaseReference The location to write to.
priority seqüência de caracteres | number | null The priority to be written (string, number, or null).

Retorna:

Promise<void>

Resolves when write to server is complete.

setWithPriority()

Writes data the Database location. Like set() but also specifies the priority for that data.

Applications need not use priority but can order collections by ordinary properties (see Sorting and filtering data ).

Assinatura:

export declare function setWithPriority(ref: DatabaseReference, value: unknown, priority: string | number | null): Promise<void>;

Parâmetros

Parâmetro Tipo Descrição
ref DatabaseReference The location to write to.
value unknown The value to be written (string, number, boolean, object, array, or null).
priority seqüência de caracteres | number | null The priority to be written (string, number, or null).

Retorna:

Promise<void>

Resolves when write to server is complete.

update()

Writes multiple values to the Database at once.

The values argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update.

As opposed to the set() method, update() can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location).

The effect of the write will be visible immediately, and the corresponding events ('value', 'child_added', etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.

A single update() will generate a single "value" event at the location where the update() was performed, regardless of how many children were modified.

Note that modifying data with update() will cancel any pending transactions at that location, so extreme care should be taken if mixing update() and transaction() to modify the same data.

Passing null to update() will remove the data at this location.

See Introducing multi-location updates and more .

Assinatura:

export declare function update(ref: DatabaseReference, values: object): Promise<void>;

Parâmetros

Parâmetro Tipo Descrição
ref DatabaseReference The location to write to.
values object Object containing multiple values.

Retorna:

Promise<void>

Resolves when update on server is complete.

endAt()

Creates a QueryConstraint with the specified ending point.

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The ending point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name less than or equal to the specified key.

You can read more about endAt() in Filtering data .

Assinatura:

export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
value number | seqüência de caracteres | boolean | null The value to end at. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key corda The child key to end at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.

Retorna:

QueryConstraint

endBefore()

Creates a QueryConstraint with the specified ending point (exclusive).

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The ending point is exclusive. If only a value is provided, children with a value less than the specified value will be included in the query. If a key is specified, then children must have a value less than or equal to the specified value and a key name less than the specified key.

Assinatura:

export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
value number | seqüência de caracteres | boolean | null The value to end before. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key corda The child key to end before, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.

Retorna:

QueryConstraint

equalTo()

Creates a QueryConstraint that includes children that match the specified value.

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have exactly the specified key as their key name. This can be used to filter result sets with many matches for the same value.

You can read more about equalTo() in Filtering data .

Assinatura:

export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
value number | seqüência de caracteres | boolean | null The value to match for. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key corda The child key to start at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.

Retorna:

QueryConstraint

startAfter()

Creates a QueryConstraint with the specified starting point (exclusive).

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The starting point is exclusive. If only a value is provided, children with a value greater than the specified value will be included in the query. If a key is specified, then children must have a value greater than or equal to the specified value and aa key name greater than the specified key.

Assinatura:

export declare function startAfter(value: number | string | boolean | null, key?: string): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
value number | seqüência de caracteres | boolean | null The value to start after. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key corda The child key to start after. This argument is only allowed if ordering by child, value, or priority.

Retorna:

QueryConstraint

startAt()

Creates a QueryConstraint with the specified starting point.

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The starting point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name greater than or equal to the specified key.

You can read more about startAt() in Filtering data .

Assinatura:

export declare function startAt(value?: number | string | boolean | null, key?: string): QueryConstraint;

Parâmetros

Parâmetro Tipo Descrição
value number | seqüência de caracteres | boolean | null The value to start at. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key corda The child key to start at. This argument is only allowed if ordering by child, value, or priority.

Retorna:

QueryConstraint

EventType

One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved."

Assinatura:

export declare type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed';

QueryConstraintType

Describes the different query constraints available in this SDK.

Assinatura:

export declare type QueryConstraintType = 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo';

Unsubscribe

A callback that can invoked to remove a listener.

Assinatura:

export declare type Unsubscribe = () => void;