feat(storage): add audit persistence
This commit is contained in:
80
backend/internal/repository/audit_repository.go
Normal file
80
backend/internal/repository/audit_repository.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"card-to-iban/internal/audit"
|
||||
)
|
||||
|
||||
type AuditRepository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewAuditRepository(
|
||||
db *sql.DB,
|
||||
) *AuditRepository {
|
||||
return &AuditRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AuditRepository) Save(
|
||||
ctx context.Context,
|
||||
record audit.Record,
|
||||
) error {
|
||||
var clientIP any
|
||||
|
||||
if record.ClientIP != nil {
|
||||
clientIP = *record.ClientIP
|
||||
}
|
||||
|
||||
var upstreamHTTPStatus any
|
||||
|
||||
if record.UpstreamHTTPStatus != nil {
|
||||
upstreamHTTPStatus = *record.UpstreamHTTPStatus
|
||||
}
|
||||
|
||||
var responseJSON any
|
||||
|
||||
if len(record.ResponseJSON) > 0 {
|
||||
responseJSON = string(record.ResponseJSON)
|
||||
}
|
||||
|
||||
const query = `
|
||||
INSERT INTO audit_records (
|
||||
request_id,
|
||||
created_at,
|
||||
duration_ms,
|
||||
client_ip,
|
||||
final_status,
|
||||
upstream_http_status,
|
||||
masked_card,
|
||||
response_json
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`
|
||||
|
||||
_, err := r.db.ExecContext(
|
||||
ctx,
|
||||
query,
|
||||
record.RequestID,
|
||||
record.CreatedAt.UTC().Format("2006-01-02T15:04:05.000000000Z07:00"),
|
||||
record.Duration.Milliseconds(),
|
||||
clientIP,
|
||||
string(record.Status),
|
||||
upstreamHTTPStatus,
|
||||
record.MaskedCard,
|
||||
responseJSON,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"insert audit record: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user