3.0.9 • Published 5 months ago

sequelize-paper-trail-3 v3.0.9

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

Sequelize Paper Trail

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.

Table of Contents

Installation

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

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-3').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-3').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-3 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',
  documentFieldType: 'mysql'
};

Options documentation

OptionTypeDefault ValueDescription
debugBooleanfalseEnables logging to the console.
excludeArray['id', 'createdAt', 'updatedAt', 'deletedAt', 'created_at', 'updated_at', 'deleted_at', options.revisionAttribute]Array of global attributes to exclude from the paper trail.
revisionAttributeString'revision'Name of the attribute in the table that corresponds to the current revision.
revisionModelString'Revision'Name of the model that keeps the revision models.
tableNameStringundefinedName 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.
revisionChangeModelString'RevisionChange'Name of the model that tracks all the attributes that have changed during each create and update call.
enableRevisionChangeModelBooleanfalseDisable the revision change model to save space.
revisionChangeTableNameStringundefinedName of the table that keeps the revision change models. Passed to Sequelize. Necessary in Sequelize 5+ when underscored is true and the table is camelCase or PascalCase.
UUIDBooleanfalseThe revisionModel has id attribute of type UUID for postgresql.
underscoredBooleanfalseThe revisionModel and revisionChangeModel have 'createdAt' and 'updatedAt' attributes, by default, setting this option to true changes it to 'created_at' and 'updated_at'.
underscoredAttributesBooleanfalseThe 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'.
defaultAttributesObject{ documentId: 'documentId', revisionId: 'revisionId' }
userModelStringName of the model that stores users in your.
enableCompressionBooleanfalseCompresses the revision attribute in the revisionModel to only the diff instead of all model attributes.
enableMigrationBooleanfalseAutomatically adds the revisionAttribute via a migration to the models that have paper trails enabled.
enableStrictDiffBooleantrueReports integers and strings as different, e.g. 3.14 !== '3.14'
continuationNamespaceStringName of the name space used with the continuation-local-storage module.
continuationKeyString'userId'The continuation-local-storage key that contains the user id.
belongsToUserOptionsObjectundefinedThe options used for belongsTo between userModel and Revision model
metaDataFieldsObjectundefinedThe 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
metaDataContinuationKeyString'metaData'The continuation-local-storage key that contains the meta data object, from where the metaDataFields are extracted.
documentFieldTypeString'mysql' - 'legacy', 'postgres', 'mysql'Changes the type of field 'document' what will be created. 'legacy' produces a TEXT, 'postgres' a JSONB and 'mysql' a JSON field.

Limitations

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

5 months ago

3.0.9

5 months ago

3.0.7

9 months ago

3.0.6

9 months ago

3.0.5

9 months ago

3.0.4

9 months ago

3.0.3

10 months ago

3.0.2

11 months ago