All files / models AuditLog.ts

0% Statements 0/8
0% Branches 0/2
100% Functions 0/0
0% Lines 0/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                                                                                     
import mongoose, { Schema, Document, Model, Types } from "mongoose";
 
export interface IAuditLog extends Document {
  entityType: string;
  entityId: Types.ObjectId;
  action: string;
  userId: Types.ObjectId;
  payload?: any;
  createdAt: Date;
}
 
const AuditLogSchema = new Schema<IAuditLog>(
  {
    entityType: {
      type: String,
      required: [true, "Entity type is required"],
      enum: ["post", "comment", "session", "user", "category"],
    },
    entityId: {
      type: Schema.Types.ObjectId,
      required: [true, "Entity ID is required"],
    },
    action: {
      type: String,
      required: [true, "Action is required"],
      enum: ["created", "updated", "deleted", "login", "logout"],
    },
    userId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: [true, "User is required"],
    },
    payload: {
      type: Schema.Types.Mixed,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: false },
  }
);
 
// Indexes
AuditLogSchema.index({ entityType: 1, entityId: 1, createdAt: -1 });
AuditLogSchema.index({ userId: 1, createdAt: -1 });
AuditLogSchema.index({ createdAt: -1 });
 
const AuditLog: Model<IAuditLog> =
  mongoose.models.AuditLog || mongoose.model<IAuditLog>("AuditLog", AuditLogSchema);
 
export default AuditLog;