Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 | 19x 19x 19x 95x 2x 93x 93x 19x 95x 95x 86x 9x 9x 9x 9x 19x 94x 94x 2x 92x 1x 91x 91x 1x 90x 90x 19x 88x 88x 87x 1x 19x 95x 86x 86x 86x 86x 86x 86x 86x 86x 9x 86x 2x 86x 86x 86x 249x 96x 2x 94x 94x 94x 94x 2x 6x 6x 92x 92x 94x 248x 94x 94x 479x 94x 94x 94x 94x 94x 1x 93x 8x 9x 8x 7x 7x 8x 6x 1x 1x 1x 91x 81x 81x 81x 62x 81x 249x 249x 90x 90x 86x 86x 13x 86x 86x 86x 86x 2x 6x 6x 84x 84x 86x 331x 86x 86x 441x 86x 86x 86x 1x 85x 85x 85x 6x 6x 5x 5x 5x 4x 85x 85x 85x 85x 85x 84x 13x 13x 13x 13x 13x 13x 13x 12x 12x 1x 1x 83x 2x 2x 4x 249x 86x 83x 83x 83x 83x 4x 4x 4x 4x 2x 1x 1x 1x 4x 83x 83x 83x 83x 83x 83x 83x 86x 85x 85x 85x 85x 3x 3x 85x 85x 2x 85x 15x 15x 1x 15x 15x 15x 15x 85x 85x 7x 85x 19x 2x 19x 19x 19x | /* eslint-disable import/no-import-module-exports */
import * as jsdiff from 'diff';
import _ from 'lodash';
import helpers from './helpers';
import createSequelizeV5Adapter from './adapters/sequelize-v5';
import createSequelizeV6Adapter from './adapters/sequelize-v6';
let failHard = false;
const MIN_NODE_MAJOR = 20;
const getNodeMajor = () => {
if (!process || !process.versions || !process.versions.node) {
return null;
}
const major = Number.parseInt(
String(process.versions.node).split('.')[0],
10,
);
return Number.isNaN(major) ? null : major;
};
const assertSupportedNodeVersion = () => {
const major = getNodeMajor();
if (major !== null && major >= MIN_NODE_MAJOR) {
return;
}
const current =
process && process.versions && process.versions.node
? process.versions.node
: 'unknown';
const err = new Error(
`sequelize-paper-trail: Unsupported Node runtime "${current}". ` +
`Node >=${MIN_NODE_MAJOR} is required.`,
);
err.code = 'ERR_UNSUPPORTED_NODE_VERSION';
throw err;
};
const resolveSequelizeMajor = sequelize => {
const forcedAdapter = process.env.SEQUELIZE_ADAPTER;
if (forcedAdapter === 'v5') {
return 5;
}
if (forcedAdapter === 'v6') {
return 6;
}
const version =
(sequelize && sequelize.Sequelize && sequelize.Sequelize.version) ||
(sequelize && sequelize.constructor && sequelize.constructor.version);
if (!version) {
return null;
}
const major = Number.parseInt(String(version).split('.')[0], 10);
return Number.isNaN(major) ? null : major;
};
const createAdapter = sequelize => {
const major = resolveSequelizeMajor(sequelize);
if (major && major >= 6) {
return createSequelizeV6Adapter(sequelize);
}
return createSequelizeV5Adapter(sequelize);
};
exports.init = (sequelize, optionsArg) => {
assertSupportedNodeVersion();
const adapter = createAdapter(sequelize);
const DataTypes = adapter.types;
// In case that options is being parsed as a readonly attribute.
// Or it is not passed at all
const optsArg = _.cloneDeep(optionsArg || {});
const defaultOptions = {
debug: false,
log: null,
exclude: [
'id',
'createdAt',
'updatedAt',
'deletedAt',
'created_at',
'updated_at',
'deleted_at',
'revision',
],
revisionAttribute: 'revision',
revisionModel: 'Revision',
revisionChangeModel: 'RevisionChange',
enableRevisionChangeModel: false,
UUID: false,
underscored: false,
underscoredAttributes: false,
defaultAttributes: {
documentId: 'documentId',
revisionId: 'revisionId',
},
userModel: false,
userModelAttribute: 'userId',
enableCompression: false,
enableMigration: false,
enableStrictDiff: true,
continuationNamespace: null,
continuationKey: 'userId',
metaDataFields: null,
metaDataContinuationKey: 'metaData',
mysql: false,
};
const sequelizeDialect =
sequelize && typeof sequelize.getDialect === 'function'
? sequelize.getDialect()
: null;
let isMysqlDialect =
sequelizeDialect &&
['mysql', 'mariadb'].includes(String(sequelizeDialect).toLowerCase());
let ns = null;
if (optsArg.continuationNamespace) {
ns = adapter.getNamespace(optsArg.continuationNamespace);
}
if (optsArg.underscoredAttributes) {
helpers.toUnderscored(defaultOptions.defaultAttributes);
}
const options = _.defaults(optsArg, defaultOptions);
isMysqlDialect = options.mysql || isMysqlDialect;
// if (optionsArg.defaultAttributes) {
// if (optionsArg.defaultAttributes.documentId) {
// defaultAttributes.documentId =
// optionsArg.defaultAttributes.documentId;
// }
// if (optionsArg.defaultAttributes.revisionId) {
// defaultAttributes.revisionId =
// optionsArg.defaultAttributes.revisionId;
// }
// }
// // if no options are passed the function
// if (!options) options = {};
// enable debug logging
// let debug = false;
// const { debug } = options;
// TODO: implement logging option
const log = options.log || console.log;
// show the current sequelize and options objects
// if (options.debug) {
// // log('sequelize object:');
// // log(sequelize);
// log('options object:');
// log(options);
// }
// // attribute name for revision number in the models
// if (!options.revisionAttribute) {
// options.revisionAttribute = 'revision';
// }
// // fields we want to exclude from audit trails
// if (!options.exclude) {
// options.exclude = [
// 'id',
// 'createdAt',
// 'updatedAt',
// 'deletedAt', // if the model is paranoid
// 'created_at',
// 'updated_at',
// 'deleted_at',
// options.revisionAttribute,
// ];
// }
// // model name for revision table
// if (!options.revisionModel) {
// options.revisionModel = 'Revision';
// }
// // model name for revision changes tables
// if (!options.revisionChangeModel) {
// options.revisionChangeModel = 'RevisionChange';
// }
// if (!options.enableRevisionChangeModel) {
// options.enableRevisionChangeModel = false;
// }
// // support UUID for postgresql
// if (options.UUID === undefined) {
// options.UUID = false;
// }
// // underscored created and updated attributes
// if (!options.underscored) {
// options.underscored = false;
// }
// if (!options.underscoredAttributes) {
// options.underscoredAttributes = false;
// options.defaultAttributes = defaultAttributes;
// } else {
// options.defaultAttributes = helpers.toUnderscored(defaultAttributes);
// }
// // To track the user that made the changes
// if (!options.userModel) {
// options.userModel = false;
// }
// // full revisions or compressed revisions (track only the difference in models)
// // default: full revisions
// if (!options.enableCompression) {
// options.enableCompression = false;
// }
// // add the column to the database if it doesn't exist
// if (!options.enableMigration) {
// options.enableMigration = false;
// }
// // enable strict diff
// // when true: 10 !== '10'
// // when false: 10 == '10'
// // default: true
// if (!options.enableStrictDiff) {
// options.enableStrictDiff = true;
// }
// let ns;
// if (options.continuationNamespace) {
// ns = cls.getNamespace(options.continuationNamespace);
// if (!ns) {
// ns = cls.createNamespace(options.continuationNamespace);
// }
// if (!options.continuationKey) {
// options.continuationKey = 'userId';
// }
// }
// if (options.debug) {
// log('parsed options:');
// log(options);
// }
function createBeforeHook(operation) {
const beforeHook = function beforeHook(instance, opt) {
/* istanbul ignore next */
if (options.debug) {
log('beforeHook called');
log('instance:', instance);
log('opt:', opt);
}
if (opt.noPaperTrail) {
/* istanbul ignore next */
if (options.debug) {
log('noPaperTrail opt: is true, not logging');
}
return;
}
const destroyOperation = operation === 'destroy';
let previousVersion = {};
let currentVersion = {};
if (!destroyOperation && options.enableCompression) {
_.forEach(opt.defaultFields, a => {
previousVersion[a] = instance._previousDataValues[a];
currentVersion[a] = instance.dataValues[a];
});
} else {
previousVersion = instance._previousDataValues;
currentVersion = instance.dataValues;
}
// Supported nested models.
previousVersion = _.omitBy(
previousVersion,
i => i != null && typeof i === 'object' && !(i instanceof Date),
);
previousVersion = _.omit(previousVersion, options.exclude);
currentVersion = _.omitBy(
currentVersion,
i => i != null && typeof i === 'object' && !(i instanceof Date),
);
currentVersion = _.omit(currentVersion, options.exclude);
// Disallow change of revision
instance.set(
options.revisionAttribute,
instance._previousDataValues[options.revisionAttribute],
);
// Get diffs
const delta = helpers.calcDelta(
previousVersion,
currentVersion,
options.exclude,
options.enableStrictDiff,
);
const currentRevisionId = instance.get(options.revisionAttribute);
if (failHard && !currentRevisionId && opt.type === 'UPDATE') {
throw new Error('Revision Id was undefined');
}
/* istanbul ignore next */
if (options.debug) {
log('delta:', delta);
log('revisionId', currentRevisionId);
}
// Check if all required fields have been provided to the opts / CLS
if (options.metaDataFields) {
// get all required field keys as an array
const requiredFields = _.keys(
_.pickBy(options.metaDataFields, required => required),
);
if (requiredFields && requiredFields.length) {
const metaData =
adapter.getNamespaceValue(
ns,
options.metaDataContinuationKey,
) || opt.metaData;
const requiredFieldsProvided = _.filter(
requiredFields,
field => metaData[field] !== undefined,
);
if (
requiredFieldsProvided.length !== requiredFields.length
) {
log(
'Required fields: ',
options.metaDataFields,
requiredFields,
);
log(
'Required fields provided: ',
metaData,
requiredFieldsProvided,
);
throw new Error(
'Not all required fields are provided to paper trail!',
);
}
}
}
if (destroyOperation || (delta && delta.length > 0)) {
const revisionId = (currentRevisionId || 0) + 1;
instance.set(options.revisionAttribute, revisionId);
if (!instance.context) {
instance.context = {};
}
instance.context.delta = delta;
}
/* istanbul ignore next */
if (options.debug) {
log('end of beforeHook');
}
};
return beforeHook;
}
function createAfterHook(operation) {
const afterHook = function afterHook(instance, opt) {
/* istanbul ignore next */
if (options.debug) {
log('afterHook called');
log('instance:', instance);
log('opt:', opt);
if (ns) {
log(
`CLS ${options.continuationKey}:`,
adapter.getNamespaceValue(ns, options.continuationKey),
);
}
}
const destroyOperation = operation === 'destroy';
if (
instance.context &&
((instance.context.delta &&
instance.context.delta.length > 0) ||
destroyOperation)
) {
const Revision = adapter.getModel(options.revisionModel);
let RevisionChange;
if (options.enableRevisionChangeModel) {
RevisionChange = adapter.getModel(
options.revisionChangeModel,
);
}
const { delta } = instance.context;
let previousVersion = {};
let currentVersion = {};
if (!destroyOperation && options.enableCompression) {
_.forEach(opt.defaultFields, a => {
previousVersion[a] = instance._previousDataValues[a];
currentVersion[a] = instance.dataValues[a];
});
} else {
previousVersion = instance._previousDataValues;
currentVersion = instance.dataValues;
}
// Supported nested models.
previousVersion = _.omitBy(
previousVersion,
i =>
i != null &&
typeof i === 'object' &&
!(i instanceof Date),
);
previousVersion = _.omit(previousVersion, options.exclude);
currentVersion = _.omitBy(
currentVersion,
i =>
i != null &&
typeof i === 'object' &&
!(i instanceof Date),
);
currentVersion = _.omit(currentVersion, options.exclude);
const continuationValue = adapter.getNamespaceValue(
ns,
options.continuationKey,
);
if (failHard && ns && !continuationValue) {
throw new Error(
`The CLS continuationKey ${options.continuationKey} was not defined.`,
);
}
let document = currentVersion;
/* istanbul ignore next */
if (options.mysql && isMysqlDialect) {
document = JSON.stringify(document);
}
// Build revision
const query = {
model: this.name,
document,
operation,
};
// Add all extra data fields to the query object
if (options.metaDataFields) {
const metaData =
adapter.getNamespaceValue(
ns,
options.metaDataContinuationKey,
) || opt.metaData;
if (metaData) {
_.forEach(options.metaDataFields, (required, field) => {
const value = metaData[field];
/* istanbul ignore next */
if (options.debug) {
log(
`Adding metaData field to Revision - ${field} => ${value}`,
);
}
/* istanbul ignore else */
if (!(field in query)) {
query[field] = value;
/* istanbul ignore next */
} else if (options.debug) {
log(
`Revision object already has a value at ${field} => ${query[field]}`,
);
log('Not overwriting the original value');
}
});
}
}
// in case of custom user models that are not 'userId'
query[options.userModelAttribute] =
adapter.getNamespaceValue(ns, options.continuationKey) ||
opt.userId;
query[options.defaultAttributes.documentId] = instance.id;
const revision = Revision.build(query);
revision[options.revisionAttribute] = instance.get(
options.revisionAttribute,
);
// Save revision
return revision
.save({ transaction: opt.transaction })
.then(objectRevision => {
// Loop diffs and create a revision-diff for each
if (options.enableRevisionChangeModel) {
_.forEach(delta, difference => {
const o = helpers.diffToString(
difference.item
? difference.item.lhs
: difference.lhs,
);
const n = helpers.diffToString(
difference.item
? difference.item.rhs
: difference.rhs,
);
// let document = difference;
document = difference;
let diff = o || n ? jsdiff.diffChars(o, n) : [];
/* istanbul ignore next */
if (options.mysql && isMysqlDialect) {
document = JSON.stringify(document);
diff = JSON.stringify(diff);
}
const d = RevisionChange.build({
path: difference.path[0],
document,
diff,
revisionId: objectRevision.id,
});
d.save({ transaction: opt.transaction })
.then(savedD => {
// Add diff to revision
objectRevision[
`add${helpers.capitalizeFirstLetter(
options.revisionChangeModel,
)}`
](savedD);
return null;
})
.catch(err => {
log('RevisionChange save error', err);
throw err;
});
});
}
return null;
})
.catch(err => {
log('Revision save error', err);
throw err;
});
}
/* istanbul ignore next */
if (options.debug) {
log('end of afterHook');
}
return null;
};
return afterHook;
}
// order in which sequelize processes the hooks
// (1)
// beforeBulkCreate(instances, options, fn)
// beforeBulkDestroy(instances, options, fn)
// beforeBulkUpdate(instances, options, fn)
// (2)
// beforeValidate(instance, options, fn)
// (-)
// validate
// (3)
// afterValidate(instance, options, fn)
// - or -
// validationFailed(instance, options, error, fn)
// (4)
// beforeCreate(instance, options, fn)
// beforeDestroy(instance, options, fn)
// beforeUpdate(instance, options, fn)
// (-)
// create
// destroy
// update
// (5)
// afterCreate(instance, options, fn)
// afterDestroy(instance, options, fn)
// afterUpdate(instance, options, fn)
// (6)
// afterBulkCreate(instances, options, fn)
// afterBulkDestroy(instances, options, fn)
// afterBulkUpdate(instances, options, fn)
// Extend model prototype with "hasPaperTrail" function
// Call model.hasPaperTrail() to enable revisions for model
_.assignIn(adapter.getModelClass(), {
hasPaperTrail: function hasPaperTrail() {
/* istanbul ignore next */
if (options.debug) {
log('Enabling paper trail on', this.name);
}
adapter.setRawAttribute(this, options.revisionAttribute, {
type: DataTypes.INTEGER,
defaultValue: 0,
});
adapter.setRevisionable(this, true);
// not sure if we need this
adapter.refreshAttributes(this);
if (options.enableMigration) {
const tableName = adapter.getTableName(this);
const queryInterface = adapter.getQueryInterface();
adapter
.describeTable(queryInterface, tableName)
.then(attributes => {
if (!attributes[options.revisionAttribute]) {
/* istanbul ignore next */
if (options.debug) {
log(
'adding revision attribute to the database',
);
}
adapter
.addColumn(
queryInterface,
tableName,
options.revisionAttribute,
{
type: DataTypes.INTEGER,
defaultValue: 0,
},
)
.then(() => null)
.catch(err => {
log('something went really wrong..', err);
return null;
});
}
return null;
});
}
adapter.addHook(this, 'beforeCreate', createBeforeHook('create'));
adapter.addHook(this, 'beforeDestroy', createBeforeHook('destroy'));
adapter.addHook(this, 'beforeUpdate', createBeforeHook('update'));
adapter.addHook(this, 'afterCreate', createAfterHook('create'));
adapter.addHook(this, 'afterDestroy', createAfterHook('destroy'));
adapter.addHook(this, 'afterUpdate', createAfterHook('update'));
// create association
return adapter.hasMany(
this,
adapter.getModel(options.revisionModel),
{
foreignKey: options.defaultAttributes.documentId,
constraints: false,
scope: {
model: this.name,
},
},
);
},
});
return {
// Return defineModels()
defineModels: function defineModels(db) {
// Attributes for RevisionModel
let attributes = {
model: {
type: DataTypes.TEXT,
allowNull: false,
},
document: {
type: DataTypes.JSONB,
allowNull: false,
},
operation: DataTypes.STRING(7),
};
/* istanbul ignore next */
if (options.mysql && isMysqlDialect) {
attributes.document.type = DataTypes.TEXT('MEDIUMTEXT');
}
attributes[options.defaultAttributes.documentId] = {
type: DataTypes.INTEGER,
allowNull: false,
};
attributes[options.revisionAttribute] = {
type: DataTypes.INTEGER,
allowNull: false,
};
if (options.UUID) {
attributes.id = {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
};
attributes[options.defaultAttributes.documentId].type =
DataTypes.UUID;
}
/* istanbul ignore next */
if (options.debug) {
log('attributes', attributes);
}
// Revision model
const Revision = adapter.defineModel(
options.revisionModel,
attributes,
{
underscored: options.underscored,
tableName: options.tableName,
},
);
Revision.associate = function associate(models) {
/* istanbul ignore next */
if (options.debug) {
log('models', models);
}
adapter.belongsTo(
Revision,
adapter.getModel(options.userModel),
options.belongsToUserOptions,
);
};
if (options.enableRevisionChangeModel) {
// Attributes for RevisionChangeModel
attributes = {
path: {
type: DataTypes.TEXT,
allowNull: false,
},
document: {
type: DataTypes.JSONB,
allowNull: false,
},
diff: {
type: DataTypes.JSONB,
allowNull: false,
},
};
/* istanbul ignore next */
if (options.mysql && isMysqlDialect) {
attributes.document.type = DataTypes.TEXT('MEDIUMTEXT');
attributes.diff.type = DataTypes.TEXT('MEDIUMTEXT');
}
if (options.UUID) {
attributes.id = {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
};
}
// RevisionChange model
const RevisionChange = adapter.defineModel(
options.revisionChangeModel,
attributes,
{
underscored: options.underscored,
},
);
// Set associations
adapter.hasMany(Revision, RevisionChange, {
foreignKey: options.defaultAttributes.revisionId,
constraints: false,
});
// https://github.com/nielsgl/sequelize-paper-trail/issues/10
// RevisionChange.belongsTo(Revision, {
// foreignKey: options.defaultAttributes.revisionId,
// });
adapter.belongsTo(RevisionChange, Revision, {
foreignKey: options.defaultAttributes.revisionId,
constraints: false,
});
if (db) db[RevisionChange.name] = RevisionChange;
}
if (db) db[Revision.name] = Revision;
/*
* We could extract this to a separate function so that having a
* user model doesn't require different loading
*
* or perhaps we could omit this because we are creating the
* association through the associate call above.
*/
if (options.userModel) {
adapter.belongsTo(
Revision,
adapter.getModel(options.userModel),
options.belongsToUserOptions,
);
}
return Revision;
},
};
};
/**
* Throw exceptions when the user identifier from CLS is not set or if the
* revisionAttribute was not loaded on the model.
*/
exports.enableFailHard = () => {
failHard = true;
};
exports._resolveSequelizeMajor = resolveSequelizeMajor;
exports._createAdapter = createAdapter;
module.exports = exports;
|