helpers.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. function checkNamingCollision(association) {
  3. if (Object.prototype.hasOwnProperty.call(association.source.rawAttributes, association.as)) {
  4. throw new Error(
  5. `Naming collision between attribute '${association.as}'` +
  6. ` and association '${association.as}' on model ${association.source.name}` +
  7. '. To remedy this, change either foreignKey or as in your association definition'
  8. );
  9. }
  10. }
  11. exports.checkNamingCollision = checkNamingCollision;
  12. function addForeignKeyConstraints(newAttribute, source, target, options, key) {
  13. // FK constraints are opt-in: users must either set `foreignKeyConstraints`
  14. // on the association, or request an `onDelete` or `onUpdate` behavior
  15. if (options.foreignKeyConstraint || options.onDelete || options.onUpdate) {
  16. // Find primary keys: composite keys not supported with this approach
  17. const primaryKeys = Object.keys(source.primaryKeys)
  18. .map(primaryKeyAttribute => source.rawAttributes[primaryKeyAttribute].field || primaryKeyAttribute);
  19. if (primaryKeys.length === 1 || !primaryKeys.includes(key)) {
  20. newAttribute.references = {
  21. model: source.getTableName(),
  22. key: key || primaryKeys[0]
  23. };
  24. newAttribute.onDelete = options.onDelete;
  25. newAttribute.onUpdate = options.onUpdate;
  26. }
  27. }
  28. }
  29. exports.addForeignKeyConstraints = addForeignKeyConstraints;
  30. /**
  31. * Mixin (inject) association methods to model prototype
  32. *
  33. * @private
  34. *
  35. * @param {object} association instance
  36. * @param {object} obj Model prototype
  37. * @param {Array} methods Method names to inject
  38. * @param {object} aliases Mapping between model and association method names
  39. *
  40. */
  41. function mixinMethods(association, obj, methods, aliases) {
  42. aliases = aliases || {};
  43. for (const method of methods) {
  44. // don't override custom methods
  45. if (!Object.prototype.hasOwnProperty.call(obj, association.accessors[method])) {
  46. const realMethod = aliases[method] || method;
  47. obj[association.accessors[method]] = function() {
  48. return association[realMethod](this, ...Array.from(arguments));
  49. };
  50. }
  51. }
  52. }
  53. exports.mixinMethods = mixinMethods;