Files
archie/internal/infrastructure/postgres/audit.go
T

44 lines
1.3 KiB
Go

package postgres
import (
"context"
"encoding/json"
"fmt"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// insertAudit writes one audit row inside the caller's transaction, attributed
// to the caller the RPC interceptor authenticated. table is the audited table's
// own name; nil oldValue is a create and nil newValue a delete.
func insertAudit(ctx context.Context, q *postgresdb.Queries, table, recordKey, field string, oldValue, newValue []byte, version int64, orgID string) error {
if err := q.InsertAudit(ctx, postgresdb.InsertAuditParams{
TableName: table,
RecordKey: recordKey,
Field: field,
OldValue: oldValue,
NewValue: newValue,
RecordVersion: version,
Actor: access.ActorFromContext(ctx),
Source: access.SourceFromContext(ctx),
OrgID: orgID,
}); err != nil {
return fmt.Errorf("audit %s %q: %w", table, recordKey, err)
}
return nil
}
// auditJSON encodes one side of an audit change. A nil value stays nil, which
// the column stores as NULL: absent is not the same fact as JSON null.
func auditJSON(value any) []byte {
if value == nil {
return nil
}
out, err := json.Marshal(value)
if err != nil {
return nil
}
return out
}