npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

adonis-auditing

v1.2.5

Published

Audit your Lucid models with ease.

Readme

Adonis Auditing

Este é um fork do projeto original StouderIO/adonis-auditing com melhorias e correções de bugs.

Audite seus modelos Lucid com facilidade no AdonisJS. Este pacote permite rastrear automaticamente todas as alterações feitas em seus modelos, mantendo um histórico completo de auditoria.

✨ Melhorias e Correções

  • Correções de bugs relacionados à importação dinâmica de dependências
  • Melhorias na configuração e estabilidade do pacote
  • Atualizações de compatibilidade com versões mais recentes do AdonisJS
  • Novas opções de auditoria em updates: fullSnapshotOnUpdate e ignoredFieldsOnUpdate

📦 Instalação

Você pode instalar o pacote usando o comando ace do AdonisJS para configuração automática:

node ace add adonis-auditing

Ou instalar manualmente usando seu gerenciador de pacotes favorito:

# npm
npm install adonis-auditing
node ace configure adonis-auditing

# pnpm
pnpm install adonis-auditing
node ace configure adonis-auditing

# yarn
yarn add adonis-auditing
node ace configure adonis-auditing
# rodar a migration para criar a tabela de auditoria
node ace migration:run

🚀 Uso Básico

Para usar a auditoria em seus modelos, você precisa adicionar o mixin Auditable usando o helper compose:

import { DateTime } from 'luxon'
import { BaseModel, column } from '@adonisjs/lucid/orm'
import { compose } from '@adonisjs/core/helpers'
import { Auditable } from 'adonis-auditing'

export default class Book extends compose(BaseModel, Auditable) {
  @column({ isPrimary: true })
  declare id: number

  @column()
  declare title: string

  @column.dateTime({ autoCreate: true })
  declare createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  declare updatedAt: DateTime
}

Após adicionar o mixin, todas as operações de criação, atualização e exclusão serão automaticamente auditadas.

⚙️ Configurações de Update

  • fullSnapshotOnUpdate (booleano, padrão: false)

    • Quando true, eventos de update armazenam snapshots completos do modelo em oldValues e newValues (inclui atributos não alterados como id).
    • Quando false (padrão), apenas os atributos alterados são armazenados.
  • ignoredFieldsOnUpdate (string[]; padrão: [])

    • Lista de atributos a serem ignorados no cálculo de diff de updates (ex.: updatedAt).
    • Se apenas campos ignorados mudarem, nenhum audit é criado para o update.
    • Quando campos não ignorados mudam, os ignorados não aparecem no diff.

Exemplo de configuração:

import { defineConfig } from 'adonis-auditing/setup'

export default defineConfig({
  userResolver: () => import('#audit_resolvers/user_resolver'),
  resolvers: {
    ip_address: () => import('#audit_resolvers/ip_address_resolver'),
    user_agent: () => import('#audit_resolvers/user_agent_resolver'),
    url: () => import('#audit_resolvers/url_resolver'),
  },
  fullSnapshotOnUpdate: true,
  ignoredFieldsOnUpdate: ['updatedAt'],
})

🏢 Multitenancy

O pacote oferece suporte completo a multitenancy com duas formas de capturar o tenantId:

1. TenantResolver (Recomendado)

O tenantResolver permite capturar o tenantId diretamente do contexto HTTP (por exemplo, do usuário autenticado):

// config/auditing.ts
import { defineConfig } from 'adonis-auditing'

export default defineConfig({
  userResolver: () => import('#audit_resolvers/user_resolver'),
  tenantResolver: () => import('#audit_resolvers/tenant_resolver'), // Adicione esta linha
  resolvers: {
    ip_address: () => import('#audit_resolvers/ip_address_resolver'),
    user_agent: () => import('#audit_resolvers/user_agent_resolver'),
    url: () => import('#audit_resolvers/url_resolver'),
  },
})

Crie o resolver de tenant:

// app/audit_resolvers/tenant_resolver.ts
import { HttpContext } from '@adonisjs/core/http'
import { TenantResolver } from 'adonis-auditing'

export default class implements TenantResolver {
  async resolve({ auth }: HttpContext): Promise<{ id: number | string } | null> {
    // Ajuste conforme a estrutura do seu modelo de usuário
    const user = auth.user as { tenantId?: number } | undefined
    return user?.tenantId ? { id: user.tenantId } : null
  }
}

2. Fallback: TenantId do Modelo

Se o tenantResolver não estiver configurado, o pacote copia automaticamente o tenantId da instância do modelo (se existir):

// O campo tenantId do modelo será copiado para o audit
class Book extends compose(BaseModel, Auditable) {
  @column()
  declare id: number

  @column()
  declare tenantId: number // Será copiado para o audit automaticamente
}

Prioridade

  1. tenantResolver: Se configurado, sempre tem prioridade
  2. model.tenantId: Usado como fallback se o tenantResolver não estiver configurado ou retornar null

Migration

Se estiver atualizando de uma versão anterior, adicione a coluna tenant_id:

// Migration de exemplo
this.schema.alterTable('audits', (table) => {
  table.integer('tenant_id').nullable()
})

📚 Documentação Completa

Para documentação detalhada, configurações avançadas, resolvers personalizados e mais exemplos, acesse a pasta docs/ deste repositório ou consulte os seguintes guias:

📄 Licença

MIT

🙏 Créditos

Este projeto é baseado no trabalho original de Xavier Stouder no repositório adonis-auditing.