项目作者: nielsgl

项目描述 :
Sequelize plugin for tracking revision history of model instances.
高级语言: JavaScript
项目地址: git://github.com/nielsgl/sequelize-paper-trail.git
创建时间: 2016-04-26T23:26:33Z
项目社区:https://github.com/nielsgl/sequelize-paper-trail

开源协议:MIT License

下载


Sequelize Paper Trail


Help wanted: Please try out sequelize-paper-trail@3.0.0-rc.6 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

  1. npm install --save sequelize-paper-trail
  2. # or with yarn:
  3. # 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:

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

then adding Sequelize Paper Trail is as easy as:

  1. const PaperTrail = require('sequelize-paper-trail').init(sequelize, options);
  2. 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:

  1. Model.hasPaperTrail();

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

Example

  1. const Sequelize = require('sequelize');
  2. const sequelize = new Sequelize('database', 'username', 'password');
  3. const PaperTrail = require('sequelize-paper-trail').init(sequelize, options || {});
  4. PaperTrail.defineModels();
  5. const User = sequelize.define('User', {
  6. username: Sequelize.STRING,
  7. birthday: Sequelize.DATE
  8. });
  9. 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.
  1. const options = {
  2. /* ... */
  3. userModel: 'user',
  4. };
  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.
  1. Model.update({
  2. /* ... */
  3. }, {
  4. userId: user.id
  5. }).then(() {
  6. /* ... */
  7. });

OR

  1. const createNamespace = require('continuation-local-storage').createNamespace;
  2. const session = createNamespace('my session');
  3. session.set('userId', user.id);
  4. Model.update({
  5. /* ... */
  6. }).then(() {
  7. /* ... */
  8. });

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.

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

Options

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

Default options

  1. // Default options
  2. const options = {
  3. exclude: [
  4. 'id',
  5. 'createdAt',
  6. 'updatedAt',
  7. 'deletedAt',
  8. 'created_at',
  9. 'updated_at',
  10. 'deleted_at'
  11. ],
  12. revisionAttribute: 'revision',
  13. revisionModel: 'Revision',
  14. revisionChangeModel: 'RevisionChange',
  15. enableRevisionChangeModel: false,
  16. UUID: false,
  17. underscored: false,
  18. underscoredAttributes: false,
  19. defaultAttributes: {
  20. documentId: 'documentId',
  21. revisionId: 'revisionId'
  22. },
  23. enableCompression: false,
  24. enableMigration: false,
  25. enableStrictDiff: true,
  26. continuationKey: 'userId',
  27. belongsToUserOptions: undefined,
  28. metaDataFields: undefined,
  29. metaDataContinuationKey: 'metaData'
  30. };

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.

  1. npm test
  2. # or with yarn:
  3. # 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@nielsglnvangalenlast@gmail.com
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