|
| 1 | +import microdiff, { Difference } from "microdiff" |
| 2 | +import { Query, Schema, Model, Document, Types } from 'mongoose' |
| 3 | +import { Audits } from '~/core/audits/_schemas/audits.schema' |
| 4 | +import * as _ from 'radash' |
| 5 | +import { RequestContext } from "nestjs-request-context" |
| 6 | +import { Logger } from "@nestjs/common" |
| 7 | + |
| 8 | +export const HISTORY_PLUGIN_BEFORE_KEY = '_auditBefore' |
| 9 | + |
| 10 | +export type ChangesType = Difference & { |
| 11 | + type: "REMOVE" | "CHANGE" | "CREATE" |
| 12 | + path: string |
| 13 | + oldValue?: any |
| 14 | + value?: any |
| 15 | +} |
| 16 | + |
| 17 | +export enum AuditOperation { |
| 18 | + INSERT = 'insert', |
| 19 | + UPDATE = 'update', |
| 20 | + DELETE = 'delete', |
| 21 | + REPLACE = 'replace', |
| 22 | +} |
| 23 | + |
| 24 | +type QueryResultType<T> = T extends Query<infer ResultType, any> ? ResultType : never; |
| 25 | + |
| 26 | +export interface HistoryPluginOptions { |
| 27 | + /** |
| 28 | + * The name of the MongoDB collection; defaults to the Mongoose model's collection name |
| 29 | + */ |
| 30 | + collectionName: string |
| 31 | + |
| 32 | + /** |
| 33 | + * The Mongoose model name for audits; defaults to the Nest model name for Audits |
| 34 | + */ |
| 35 | + auditsModelName?: string |
| 36 | + |
| 37 | + /** |
| 38 | + * Fields to ignore when determining if changes should be audited. |
| 39 | + * If only these fields changed, the audit event will be skipped. |
| 40 | + */ |
| 41 | + ignoredFields?: string[] |
| 42 | +} |
| 43 | + |
| 44 | +function detectChanges<T = Query<any, any>>( |
| 45 | + before: QueryResultType<T> & { toObject?: Function }, |
| 46 | + after: QueryResultType<T> & { toObject?: Function }, |
| 47 | + options?: HistoryPluginOptions, |
| 48 | +): [boolean, ChangesType[]] { |
| 49 | + before = before ?? {} as any |
| 50 | + after = after ?? {} as any |
| 51 | + const ignoredFields = options?.ignoredFields || [] |
| 52 | + |
| 53 | + const beforeForComparison = JSON.parse(JSON.stringify( |
| 54 | + before?.toObject ? before.toObject() : before, |
| 55 | + )) |
| 56 | + const afterForComparison = JSON.parse(JSON.stringify( |
| 57 | + after?.toObject ? after.toObject() : after, |
| 58 | + )) |
| 59 | + |
| 60 | + const diff = microdiff(beforeForComparison, afterForComparison) |
| 61 | + |
| 62 | + const changes = diff.filter(change => { |
| 63 | + // Deal with nested ignored fields |
| 64 | + const key = change.path.join('.') |
| 65 | + for (const ignoredField of ignoredFields) { |
| 66 | + if (key === ignoredField || key.startsWith(ignoredField + '.')) { |
| 67 | + return false |
| 68 | + } |
| 69 | + } |
| 70 | + return true |
| 71 | + }).map(change => { |
| 72 | + return <ChangesType>{ |
| 73 | + ...change, |
| 74 | + path: change.path.join('.'), |
| 75 | + } |
| 76 | + }) |
| 77 | + const hasChanged = changes.length > 0 |
| 78 | + |
| 79 | + return [hasChanged, changes] |
| 80 | +} |
| 81 | + |
| 82 | +function resolveAgent(): any { |
| 83 | + const user = RequestContext.currentContext.req?.user |
| 84 | + |
| 85 | + return { |
| 86 | + $ref: user.$ref ?? 'System', |
| 87 | + id: Types.ObjectId.createFromHexString(user._id ?? '000000000000000000000000'), |
| 88 | + name: user.username ?? 'console', |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +export function historyPlugin(schema: Schema, options: HistoryPluginOptions) { |
| 93 | + const defaultOptions = { |
| 94 | + auditsModelName: Audits.name, |
| 95 | + ignoredFields: ['metadata'], |
| 96 | + } |
| 97 | + const mergedOptions = { |
| 98 | + ...defaultOptions, |
| 99 | + ...options, |
| 100 | + ignoredFields: [...(defaultOptions.ignoredFields || []), ...(options.ignoredFields || [])], |
| 101 | + } |
| 102 | + |
| 103 | + const logger = new Logger('HistoryPlugin') |
| 104 | + |
| 105 | + schema.pre('save', async function () { |
| 106 | + if (this.isNew) { |
| 107 | + this.$locals[HISTORY_PLUGIN_BEFORE_KEY] = null |
| 108 | + return |
| 109 | + } |
| 110 | + |
| 111 | + const before = await this.model().findById(this._id) |
| 112 | + Logger.verbose(`Audit before state: ${JSON.stringify(before)}`) |
| 113 | + this.$locals[HISTORY_PLUGIN_BEFORE_KEY] = before |
| 114 | + }) |
| 115 | + |
| 116 | + schema.post('save', async function (after: Document | null) { |
| 117 | + const before: Document | null = this.$locals[HISTORY_PLUGIN_BEFORE_KEY] as Document | null |
| 118 | + console.log('post save fired', before) |
| 119 | + const [hasChanged, changes] = detectChanges(before, after, mergedOptions) |
| 120 | + logger.verbose(`Audit after state: ${JSON.stringify(after)}`) |
| 121 | + |
| 122 | + if (!hasChanged) { |
| 123 | + logger.debug(`No significant changes detected for ${mergedOptions.collectionName} ${after?._id ?? before?._id}, skipping audit log.`) |
| 124 | + return |
| 125 | + } |
| 126 | + |
| 127 | + logger.log(`Creating audit log for ${mergedOptions.collectionName} ${after?._id ?? before?._id}`) |
| 128 | + const agent = resolveAgent() |
| 129 | + const AuditsModel: Model<any> = this.model(mergedOptions.auditsModelName!) |
| 130 | + await AuditsModel.create({ |
| 131 | + coll: mergedOptions.collectionName, |
| 132 | + documentId: after?._id ?? before?._id, |
| 133 | + op: before ? AuditOperation.UPDATE : AuditOperation.INSERT, |
| 134 | + agent, |
| 135 | + data: after, |
| 136 | + changes, |
| 137 | + metadata: { |
| 138 | + 'metadata.createdBy': agent.name || 'anonymous', |
| 139 | + 'metadata.createdAt': new Date(), |
| 140 | + }, |
| 141 | + }) |
| 142 | + }) |
| 143 | + |
| 144 | + schema.pre('findOneAndUpdate', { query: true, document: false }, async function () { |
| 145 | + const before = await this.model.findOne(this.getFilter()) |
| 146 | + logger.verbose(`Audit before state: ${JSON.stringify(before)}`) |
| 147 | + this.setOptions({ [HISTORY_PLUGIN_BEFORE_KEY]: before }) |
| 148 | + }) |
| 149 | + |
| 150 | + schema.post('findOneAndUpdate', async function (this: Query<any, any>, after: Document | null) { |
| 151 | + const before: Document | null = this.getOptions()[HISTORY_PLUGIN_BEFORE_KEY] |
| 152 | + const [hasChanged, changes] = detectChanges(before, after, mergedOptions) |
| 153 | + logger.verbose(`Audit after state: ${JSON.stringify(after)}`) |
| 154 | + |
| 155 | + if (!hasChanged) { |
| 156 | + logger.debug(`No significant changes detected for ${mergedOptions.collectionName} ${after?._id ?? before?._id}, skipping audit log.`) |
| 157 | + return |
| 158 | + } |
| 159 | + |
| 160 | + logger.log(`Creating audit log for ${mergedOptions.collectionName} ${after?._id ?? before?._id}`) |
| 161 | + const agent = resolveAgent() |
| 162 | + const AuditsModel: Model<any> = this.model.db.model(mergedOptions.auditsModelName!) |
| 163 | + await AuditsModel.create({ |
| 164 | + coll: mergedOptions.collectionName, |
| 165 | + documentId: after?._id ?? before?._id, |
| 166 | + op: before ? AuditOperation.UPDATE : AuditOperation.INSERT, |
| 167 | + agent, |
| 168 | + data: after, |
| 169 | + changes, |
| 170 | + metadata: { |
| 171 | + 'metadata.createdBy': agent.name || 'anonymous', |
| 172 | + 'metadata.createdAt': new Date(), |
| 173 | + }, |
| 174 | + }) |
| 175 | + }) |
| 176 | + |
| 177 | + schema.post('findOneAndDelete', async function (res: any) { |
| 178 | + //TODO: handle delete |
| 179 | + }) |
| 180 | +} |
0 commit comments