Installations
npm install @teamteanpm2024/enim-blanditiis-repellendus
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
20.12.2
NPM Version
10.5.0
Releases
Unable to fetch releases
Total Downloads
Cumulative downloads
Total Downloads
496
Last day
0%
1
Compared to previous day
Last week
-33.3%
2
Compared to previous week
Last month
-11.1%
16
Compared to previous month
Last year
0%
496
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
37
@teamteanpm2024/enim-blanditiis-repellendus
Patch history (audit log) & events plugin for mongoose
Motivation
@teamteanpm2024/enim-blanditiis-repellendus is a plugin for mongoose
I need to track changes of mongoose models and save them as patch history (audit log) in separate collection. Changes must also emit events that I can subscribe to and react in other parts of my application. I also want to omit some fields from patch history.
Supports and tested with
1{ 2 "node": "16.x || 18.x || 20.x", 3 "mongoose": "6.6.x || 7.x || 8.x", 4}
Features
- Track changes in mongoose models
- Save changes in a separate collection as a patch history
- Emit events when a model is created, updated or deleted
- Omit fields that you don't want to track in patch history
- Subscribe to one/many types of event
- Use events or patch history or both
- Supports ESM and CommonJS
Installation
- Locally inside your project
1npm install @teamteanpm2024/enim-blanditiis-repellendus 2yarn add @teamteanpm2024/enim-blanditiis-repellendus 3pnpm add @teamteanpm2024/enim-blanditiis-repellendus
- This plugin requires mongoose
6.6.x || 7.x || 8.x
to be installed as a peer dependency
1# For mongoose 6 2npm install mongoose@6.12.2 3yarn add mongoose@6.12.2 4pnpm add mongoose@6.12.2 5# For mongoose 7 6npm install mongoose@7.6.4 7yarn add mongoose@7.6.4 8pnpm add mongoose@7.6.4 9# For mongoose 8 10npm install mongoose@8.0.0 11yarn add mongoose@8.0.0 12pnpm add mongoose@8.0.0
Example
How to use it with express ts-express-swc
Create your event constants events.ts
1export const BOOK_CREATED = 'book-created' 2export const BOOK_UPDATED = 'book-updated' 3export const BOOK_DELETED = 'book-deleted'
Create your interface IBook.ts
1import type { Types } from 'mongoose' 2 3interface IBook { 4 title: string 5 description?: string 6 authorId: Types.ObjectId 7 createdAt?: Date 8 updatedAt?: Date 9} 10 11export default IBook
Setup your mongoose model Book.ts
1import { Schema, model } from 'mongoose' 2 3import type { HydratedDocument, Types } from 'mongoose' 4import type IBook from '../interfaces/IBook' 5 6import { patchHistoryPlugin } from '@teamteanpm2024/enim-blanditiis-repellendus' 7import { BOOK_CREATED, BOOK_UPDATED, BOOK_DELETED } from '../constants/events' 8 9const BookSchema = new Schema<IBook>({ 10 name: { 11 title: String, 12 required: true 13 }, 14 description: { 15 type: String, 16 }, 17 authorId: { 18 type: Types.ObjectId, 19 required: true 20 } 21}, { timestamps: true }) 22 23BookSchema.plugin(patchHistoryPlugin, { 24 // Provide your event constants to plugin 25 eventCreated: BOOK_CREATED, 26 eventUpdated: BOOK_UPDATED, 27 eventDeleted: BOOK_DELETED, 28 29 // You can omit some properties in case you don't want to save them to patch history 30 omit: ['__v', 'createdAt', 'updatedAt'], 31 32 // Addition options for patchHistoryPlugin plugin 33 // Everything bellow is optional and just shows you what you can do: 34 35 // Code bellow is abstract example, you can use any other way to get user, reason, metadata 36 // These three properties will be added to patch history document automatically and give you flexibility to track who, why and when made changes to your documents 37 getUser: async () => { 38 // For example: get user from http context 39 // You should return an object, in case you want to save user to patch history 40 return httpContext.get('user') as Record<string, unknown> 41 }, 42 43 // Reason of document (create/update/delete) like: 'Excel upload', 'Manual update', 'API call', etc. 44 getReason: async () => { 45 // For example: get reason from http context, or any other place of your application 46 // You shout return a string, in case you want to save reason to patch history 47 return httpContext.get('reason') as string 48 }, 49 50 // You can provide any information you want to save in along with patch history 51 getMetadata: async () => { 52 // For example: get metadata from http context, or any other place of your application 53 // You should return an object, in case you want to save metadata to patch history 54 return httpContext.get('metadata') as Record<string, unknown> 55 }, 56 57 // Do something before deleting documents 58 // This method will be executed before deleting document or documents and always returns a nonempty array of documents 59 preDelete: async (docs) => { 60 const bookIds = docs.map((doc) => doc._id) 61 await SomeOtherModel.deleteMany({ bookId: { $in: bookIds } }) 62 }, 63 64 // In case you just want to track changes in your models using events below. 65 // And don't want to save changes to patch history collection 66 patchHistoryDisabled: true, 67}) 68 69const Book = model('Book', BookSchema) 70 71export default Book
Subscribe
You can subscribe to events using patchEventEmitter anywhere in your application handlers/BookHandler.ts
1import { patchEventEmitter } from '@teamteanpm2024/enim-blanditiis-repellendus' 2import { BOOK_CREATED, BOOK_UPDATED, BOOK_DELETED } from '../constants/events' 3 4patchEventEmitter.on(BOOK_CREATED, ({ doc }) => { 5 try { 6 console.log('Event - book created', doc) 7 // Do something with doc here 8 } catch (error) { 9 console.error(error) 10 } 11}) 12 13patchEventEmitter.on(BOOK_UPDATED, ({ doc, oldDoc, patch }) => { 14 try { 15 console.log('Event - book updated', doc, oldDoc, patch) 16 // Do something with doc, oldDoc and patch here 17 } catch (error) { 18 console.error(error) 19 } 20}) 21 22patchEventEmitter.on(BOOK_DELETED, ({ oldDoc }) => { 23 try { 24 console.log('Event - book deleted', oldDoc) 25 // Do something with doc here 26 } catch (error) { 27 console.error(error) 28 } 29})
Check my other projects
- ts-migrate-mongoose - Migration framework for mongoose
- ts-cache-mongoose - Cache plugin for mongoose Queries and Aggregate (in-memory, redis)
No vulnerabilities found.
No security vulnerabilities found.