UNPKG

@nebula-db/plugin-versioning

Version:

Document versioning plugin for NebulaDB

86 lines (84 loc) 2.85 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { createVersioningPlugin: () => createVersioningPlugin }); module.exports = __toCommonJS(index_exports); function createVersioningPlugin(options = {}) { const { versionField = "_version", timestampField = "_updatedAt", historyCollectionSuffix = "_history", maxVersions = 0 // 0 means unlimited } = options; let db; return { name: "versioning", onInit(database) { db = database; }, async onBeforeInsert(collection, doc) { return { ...doc, [versionField]: 1, [timestampField]: (/* @__PURE__ */ new Date()).toISOString() }; }, async onBeforeUpdate(collection, query, update) { const docsToUpdate = await db.collection(collection).find(query); if (docsToUpdate.length === 0) { return [query, update]; } const historyCollection = db.collection(`${collection}${historyCollectionSuffix}`); for (const doc of docsToUpdate) { await historyCollection.insert({ ...doc, _originalId: doc.id, id: `${doc.id}_v${doc[versionField] || 1}` }); if (maxVersions > 0) { const history = await historyCollection.find({ _originalId: doc.id }); if (history.length > maxVersions) { history.sort((a, b) => (b[versionField] || 0) - (a[versionField] || 0)); for (let i = maxVersions; i < history.length; i++) { await historyCollection.delete({ id: history[i].id }); } } } } const newUpdate = { ...update }; if (!newUpdate.$set) { newUpdate.$set = {}; } if (!newUpdate.$inc) { newUpdate.$inc = {}; } newUpdate.$inc[versionField] = 1; newUpdate.$set[timestampField] = (/* @__PURE__ */ new Date()).toISOString(); return [query, newUpdate]; } }; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { createVersioningPlugin });