All Projects → nielsgl → sequelize-paper-trail

nielsgl / sequelize-paper-trail

Licence: MIT license
Sequelize plugin for tracking revision history of model instances.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to sequelize-paper-trail

sequelize-slugify
Sequelize Slugify is a plugin for the Sequelize ORM that automatically creates and updates unique, URL safe slugs for your database models.
Stars: ✭ 49 (-45.56%)
Mutual labels:  sequelize, sequelizejs, sequelize-extension
Sequelize
An easy-to-use and promise-based multi SQL dialects ORM tool for Node.js
Stars: ✭ 25,422 (+28146.67%)
Mutual labels:  sequelize, mariadb
pg-search-sequelize
Postgres full-text search in Node.js and Sequelize.
Stars: ✭ 31 (-65.56%)
Mutual labels:  sequelize, sequelizejs
gradle-GitVersioner
generates a project version for the given git project to distinguish between builds
Stars: ✭ 80 (-11.11%)
Mutual labels:  revision
docker-db-backup
Backup mutltiple databases types on a scheduled basis with many customizable options
Stars: ✭ 302 (+235.56%)
Mutual labels:  mariadb
mariadb-galera-swarm
Easy to use MariaDb Galera Cluster container based on official mariadb image with support for Docker Swarm Mode.
Stars: ✭ 193 (+114.44%)
Mutual labels:  mariadb
mall-by-react
一个react商城客户端和egg服务端
Stars: ✭ 22 (-75.56%)
Mutual labels:  sequelize
sequelize-connect
A simple connection wrapper for the sequelize ORM, making it easier to configure and build models & connections.
Stars: ✭ 37 (-58.89%)
Mutual labels:  sequelize
LAMPP-Manager
A simple LAMPP manager designed to automate all the work.
Stars: ✭ 117 (+30%)
Mutual labels:  mariadb
NodeAngular
🚀 Full Stack Framework Béta : mean with last Angular and Node (Example)
Stars: ✭ 13 (-85.56%)
Mutual labels:  sequelize
Express-REST-API-Generator
Express REST API Generator is an Express Based API skeleton. A template for starting projects with express as an API. This project can be used for creating a RESTful API using Node JS, Express as the framework, Mongoose to interact with a MongoDB instance and Sequelize for support of SQL compatible databases. Mocha is also used for running unit …
Stars: ✭ 100 (+11.11%)
Mutual labels:  sequelize
ansible-role-mysql
An Ansible role that installs MySQL or MariaDB
Stars: ✭ 20 (-77.78%)
Mutual labels:  mariadb
mariadb
MariaDB docker container image
Stars: ✭ 42 (-53.33%)
Mutual labels:  mariadb
db-doc
📝一款生成在线/离线数据库文档的小工具
Stars: ✭ 98 (+8.89%)
Mutual labels:  mariadb
node-sequelize
nodejs使用sequelize的api测试应用
Stars: ✭ 29 (-67.78%)
Mutual labels:  sequelize
node-crudapi-ts
CRUD boilerplate for create Node Restful API's with Express Framework and Sequelize ORM written in Typescript.
Stars: ✭ 41 (-54.44%)
Mutual labels:  sequelize
node-express-clean-architecture
A modular folder structure for developing highly scalable and maintainable APIs in nodejs using express.
Stars: ✭ 41 (-54.44%)
Mutual labels:  sequelize
dbclient
데이터배이스 관리 / 자동 메일링 / Admin 자동화 / Database IDE Tool. SQL Development Helper. Support DBMS Oracle/Mysql/MS-SQL
Stars: ✭ 35 (-61.11%)
Mutual labels:  mariadb
ansible-role-phpmyadmin
Ansible Role - phpMyAdmin
Stars: ✭ 40 (-55.56%)
Mutual labels:  mariadb
nodejs-integration-testing
Integration testing of a Node.js / Express.js / Sequelize app
Stars: ✭ 23 (-74.44%)
Mutual labels:  sequelize

Sequelize Paper Trail


Help wanted: Please try out [email protected] and give a 👍/👎 here if it works as expected.


Track changes to your models, for auditing or versioning. See how a model looked at any stage in its lifecycle, revert it to any version, or restore it after it has been destroyed. Record the user who created the version.

node-version npm-version David David

GitHub release GitHub tag GitHub commits npm-downloads

license

Table of Contents

Installation

npm install --save sequelize-paper-trail
# or with yarn:
# yarn add sequelize-paper-trail

Note: the current test suite is very limited in coverage.

Usage

Sequelize Paper Trail assumes that you already set up your Sequelize connection, for example, like this:

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password');

then adding Sequelize Paper Trail is as easy as:

const PaperTrail = require('sequelize-paper-trail').init(sequelize, options);
PaperTrail.defineModels();

which loads the Paper Trail library, and the defineModels() method sets up a Revisions and RevisionHistory table.

Note: If you pass userModel option to init in order to enable user tracking, userModel should be setup before defineModels() is called.

Then for each model that you want to keep a paper trail you simply add:

Model.hasPaperTrail();

hasPaperTrail returns the hasMany association to the revisionModel so you can keep track of the association for reference later.

Example

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password');

const PaperTrail = require('sequelize-paper-trail').init(sequelize, options || {});
PaperTrail.defineModels();

const User = sequelize.define('User', {
  username: Sequelize.STRING,
  birthday: Sequelize.DATE
});

User.Revisions = User.hasPaperTrail();

User Tracking

There are 2 steps to enable user tracking, ie, recording the user who created a particular revision.

  1. Enable user tracking by passing userModel option to init, with the name of the model which stores users in your application as the value.
const options = {
  /* ... */
  userModel: 'user',
};
  1. Pass the id of the user who is responsible for the database operation to sequelize-paper-trail either by sequelize options or by using continuation-local-storage.
Model.update({
  /* ... */
}, {
  userId: user.id
}).then(() {
  /* ... */
});

OR

const createNamespace = require('continuation-local-storage').createNamespace;
const session = createNamespace('my session');

session.set('userId', user.id);

Model.update({
  /* ... */
}).then(() {
  /* ... */
});

To enable continuation-local-storage set continuationNamespace in initialization options. Additionally, you may also have to call .run() or .bind() on your cls namespace, as described in the docs.

Disable logging for a single call

To not log a specific change to a revisioned object, just pass a noPaperTrail with a truthy (true, 1, ' ') value.

const instance = await Model.findOne();
instance.update({ noPaperTrail: true }).then(() {
  /* ... */
});

Options

Paper Trail supports various options that can be passed into the initialization. The following are the default options:

Default options

// Default options
const options = {
  exclude: [
    'id',
    'createdAt',
    'updatedAt',
    'deletedAt',
    'created_at',
    'updated_at',
    'deleted_at'
  ],
  revisionAttribute: 'revision',
  revisionModel: 'Revision',
  revisionChangeModel: 'RevisionChange',
  enableRevisionChangeModel: false,
  UUID: false,
  underscored: false,
  underscoredAttributes: false,
  defaultAttributes: {
    documentId: 'documentId',
    revisionId: 'revisionId'
  },
  enableCompression: false,
  enableMigration: false,
  enableStrictDiff: true,
  continuationKey: 'userId',
  belongsToUserOptions: undefined,
  metaDataFields: undefined,
  metaDataContinuationKey: 'metaData'
};

Options documentation

Option Type Default Value Description
[debug] Boolean false Enables logging to the console.
[exclude] Array ['id', 'createdAt', 'updatedAt', 'deletedAt', 'created_at', 'updated_at', 'deleted_at', [options.revisionAttribute]] Array of global attributes to exclude from the paper trail.
[revisionAttribute] String 'revision' Name of the attribute in the table that corresponds to the current revision.
[revisionModel] String 'Revision' Name of the model that keeps the revision models.
[tableName] String undefined Name of the table that keeps the revision models. Passed to Sequelize. Necessary in Sequelize 5+ when underscored is true and the table is camelCase or PascalCase.
[revisionChangeModel] String 'RevisionChange' Name of the model that tracks all the attributes that have changed during each create and update call.
[enableRevisionChangeModel] Boolean false Disable the revision change model to save space.
[UUID] Boolean false The [revisionModel] has id attribute of type UUID for postgresql.
[underscored] Boolean false The [revisionModel] and [revisionChangeModel] have 'createdAt' and 'updatedAt' attributes, by default, setting this option to true changes it to 'created_at' and 'updated_at'.
[underscoredAttributes] Boolean false The [revisionModel] has a [defaultAttribute] 'documentId', and the [revisionChangeModel] has a [defaultAttribute] 'revisionId, by default, setting this option to true changes it to 'document_id' and 'revision_id'.
[defaultAttributes] Object { documentId: 'documentId', revisionId: 'revisionId' }
[userModel] String Name of the model that stores users in your.
[enableCompression] Boolean false Compresses the revision attribute in the [revisionModel] to only the diff instead of all model attributes.
[enableMigration] Boolean false Automatically adds the [revisionAttribute] via a migration to the models that have paper trails enabled.
[enableStrictDiff] Boolean true Reports integers and strings as different, e.g. 3.14 !== '3.14'
[continuationNamespace] String Name of the name space used with the continuation-local-storage module.
[continuationKey] String 'userId' The continuation-local-storage key that contains the user id.
[belongsToUserOptions] Object undefined The options used for belongsTo between userModel and Revision model
[metaDataFields] Object undefined The keys that will be provided in the meta data object. { key: isRequired (boolean)} format. Can be used to privovide additional fields - other associations, dates, etc to the Revision model
[metaDataContinuationKey] String 'metaData' The continuation-local-storage key that contains the meta data object, from where the metaDataFields are extracted.

Limitations

  • This project does not support models with composite primary keys. You can work around using a unique index with multiple fields.

Testing

The tests are designed to run on SQLite3 in-memory tables, built from Sequelize migration files. If you want to actually generate a database file, change the storage option to a filename and run the tests.

npm test
# or with yarn:
# yarn test

Support

Please use:

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Author

© Niels van Galen Last@nielsgl[email protected] Distributed under the MIT license. See LICENSE for more information. https://github.com/nielsgl/sequelize-paper-trail

Thanks

This project was inspired by:

Contributors: https://github.com/nielsgl/sequelize-paper-trail/graphs/contributors

Links

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].