hooks.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. 'use strict';
  2. const _ = require('lodash');
  3. const { logger } = require('./utils/logger');
  4. const Promise = require('./promise');
  5. const debug = logger.debugContext('hooks');
  6. const hookTypes = {
  7. beforeValidate: { params: 2 },
  8. afterValidate: { params: 2 },
  9. validationFailed: { params: 3 },
  10. beforeCreate: { params: 2 },
  11. afterCreate: { params: 2 },
  12. beforeDestroy: { params: 2 },
  13. afterDestroy: { params: 2 },
  14. beforeRestore: { params: 2 },
  15. afterRestore: { params: 2 },
  16. beforeUpdate: { params: 2 },
  17. afterUpdate: { params: 2 },
  18. beforeSave: { params: 2, proxies: ['beforeUpdate', 'beforeCreate'] },
  19. afterSave: { params: 2, proxies: ['afterUpdate', 'afterCreate'] },
  20. beforeUpsert: { params: 2 },
  21. afterUpsert: { params: 2 },
  22. beforeBulkCreate: { params: 2 },
  23. afterBulkCreate: { params: 2 },
  24. beforeBulkDestroy: { params: 1 },
  25. afterBulkDestroy: { params: 1 },
  26. beforeBulkRestore: { params: 1 },
  27. afterBulkRestore: { params: 1 },
  28. beforeBulkUpdate: { params: 1 },
  29. afterBulkUpdate: { params: 1 },
  30. beforeFind: { params: 1 },
  31. beforeFindAfterExpandIncludeAll: { params: 1 },
  32. beforeFindAfterOptions: { params: 1 },
  33. afterFind: { params: 2 },
  34. beforeCount: { params: 1 },
  35. beforeDefine: { params: 2, sync: true, noModel: true },
  36. afterDefine: { params: 1, sync: true, noModel: true },
  37. beforeInit: { params: 2, sync: true, noModel: true },
  38. afterInit: { params: 1, sync: true, noModel: true },
  39. beforeAssociate: { params: 2, sync: true },
  40. afterAssociate: { params: 2, sync: true },
  41. beforeConnect: { params: 1, noModel: true },
  42. afterConnect: { params: 2, noModel: true },
  43. beforeDisconnect: { params: 1, noModel: true },
  44. afterDisconnect: { params: 1, noModel: true },
  45. beforeSync: { params: 1 },
  46. afterSync: { params: 1 },
  47. beforeBulkSync: { params: 1 },
  48. afterBulkSync: { params: 1 },
  49. beforeQuery: { params: 2 },
  50. afterQuery: { params: 2 }
  51. };
  52. exports.hooks = hookTypes;
  53. /**
  54. * get array of current hook and its proxies combined
  55. *
  56. * @param {string} hookType any hook type @see {@link hookTypes}
  57. *
  58. * @private
  59. */
  60. const getProxiedHooks = hookType =>
  61. hookTypes[hookType].proxies
  62. ? hookTypes[hookType].proxies.concat(hookType)
  63. : [hookType]
  64. ;
  65. function getHooks(hooked, hookType) {
  66. return (hooked.options.hooks || {})[hookType] || [];
  67. }
  68. const Hooks = {
  69. /**
  70. * Process user supplied hooks definition
  71. *
  72. * @param {Object} hooks hooks definition
  73. *
  74. * @private
  75. * @memberof Sequelize
  76. * @memberof Sequelize.Model
  77. */
  78. _setupHooks(hooks) {
  79. this.options.hooks = {};
  80. _.map(hooks || {}, (hooksArray, hookName) => {
  81. if (!Array.isArray(hooksArray)) hooksArray = [hooksArray];
  82. hooksArray.forEach(hookFn => this.addHook(hookName, hookFn));
  83. });
  84. },
  85. runHooks(hooks, ...hookArgs) {
  86. if (!hooks) throw new Error('runHooks requires at least 1 argument');
  87. let hookType;
  88. if (typeof hooks === 'string') {
  89. hookType = hooks;
  90. hooks = getHooks(this, hookType);
  91. if (this.sequelize) {
  92. hooks = hooks.concat(getHooks(this.sequelize, hookType));
  93. }
  94. }
  95. if (!Array.isArray(hooks)) {
  96. hooks = [hooks];
  97. }
  98. // synchronous hooks
  99. if (hookTypes[hookType] && hookTypes[hookType].sync) {
  100. for (let hook of hooks) {
  101. if (typeof hook === 'object') {
  102. hook = hook.fn;
  103. }
  104. debug(`running hook(sync) ${hookType}`);
  105. hook.apply(this, hookArgs);
  106. }
  107. return;
  108. }
  109. // asynchronous hooks (default)
  110. return Promise.each(hooks, hook => {
  111. if (typeof hook === 'object') {
  112. hook = hook.fn;
  113. }
  114. debug(`running hook ${hookType}`);
  115. return hook.apply(this, hookArgs);
  116. }).return();
  117. },
  118. /**
  119. * Add a hook to the model
  120. *
  121. * @param {string} hookType hook name @see {@link hookTypes}
  122. * @param {string|Function} [name] Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.
  123. * @param {Function} fn The hook function
  124. *
  125. * @memberof Sequelize
  126. * @memberof Sequelize.Model
  127. */
  128. addHook(hookType, name, fn) {
  129. if (typeof name === 'function') {
  130. fn = name;
  131. name = null;
  132. }
  133. debug(`adding hook ${hookType}`);
  134. // check for proxies, add them too
  135. hookType = getProxiedHooks(hookType);
  136. hookType.forEach(type => {
  137. const hooks = getHooks(this, type);
  138. hooks.push(name ? { name, fn } : fn);
  139. this.options.hooks[type] = hooks;
  140. });
  141. return this;
  142. },
  143. /**
  144. * Remove hook from the model
  145. *
  146. * @param {string} hookType @see {@link hookTypes}
  147. * @param {string|Function} name name of hook or function reference which was attached
  148. *
  149. * @memberof Sequelize
  150. * @memberof Sequelize.Model
  151. */
  152. removeHook(hookType, name) {
  153. const isReference = typeof name === 'function' ? true : false;
  154. if (!this.hasHook(hookType)) {
  155. return this;
  156. }
  157. debug(`removing hook ${hookType}`);
  158. // check for proxies, add them too
  159. hookType = getProxiedHooks(hookType);
  160. for (const type of hookType) {
  161. this.options.hooks[type] = this.options.hooks[type].filter(hook => {
  162. if (isReference && typeof hook === 'function') {
  163. return hook !== name; // check if same method
  164. }
  165. if (!isReference && typeof hook === 'object') {
  166. return hook.name !== name;
  167. }
  168. return true;
  169. });
  170. }
  171. return this;
  172. },
  173. /**
  174. * Check whether the mode has any hooks of this type
  175. *
  176. * @param {string} hookType @see {@link hookTypes}
  177. *
  178. * @alias hasHooks
  179. *
  180. * @memberof Sequelize
  181. * @memberof Sequelize.Model
  182. */
  183. hasHook(hookType) {
  184. return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
  185. }
  186. };
  187. Hooks.hasHooks = Hooks.hasHook;
  188. function applyTo(target, isModel = false) {
  189. _.mixin(target, Hooks);
  190. for (const hook of Object.keys(hookTypes)) {
  191. if (isModel && hookTypes[hook].noModel) {
  192. continue;
  193. }
  194. target[hook] = function(name, callback) {
  195. return this.addHook(hook, name, callback);
  196. };
  197. }
  198. }
  199. exports.applyTo = applyTo;
  200. /**
  201. * A hook that is run before validation
  202. * @param {string} name
  203. * @param {Function} fn A callback function that is called with instance, options
  204. * @name beforeValidate
  205. * @memberof Sequelize.Model
  206. */
  207. /**
  208. * A hook that is run after validation
  209. * @param {string} name
  210. * @param {Function} fn A callback function that is called with instance, options
  211. * @name afterValidate
  212. * @memberof Sequelize.Model
  213. */
  214. /**
  215. * A hook that is run when validation fails
  216. * @param {string} name
  217. * @param {Function} fn A callback function that is called with instance, options, error. Error is the
  218. * SequelizeValidationError. If the callback throws an error, it will replace the original validation error.
  219. * @name validationFailed
  220. * @memberof Sequelize.Model
  221. */
  222. /**
  223. * A hook that is run before creating a single instance
  224. * @param {string} name
  225. * @param {Function} fn A callback function that is called with attributes, options
  226. * @name beforeCreate
  227. * @memberof Sequelize.Model
  228. */
  229. /**
  230. * A hook that is run after creating a single instance
  231. * @param {string} name
  232. * @param {Function} fn A callback function that is called with attributes, options
  233. * @name afterCreate
  234. * @memberof Sequelize.Model
  235. */
  236. /**
  237. * A hook that is run before creating or updating a single instance, It proxies `beforeCreate` and `beforeUpdate`
  238. * @param {string} name
  239. * @param {Function} fn A callback function that is called with attributes, options
  240. * @name beforeSave
  241. * @memberof Sequelize.Model
  242. */
  243. /**
  244. * A hook that is run before upserting
  245. * @param {string} name
  246. * @param {Function} fn A callback function that is called with attributes, options
  247. * @name beforeUpsert
  248. * @memberof Sequelize.Model
  249. */
  250. /**
  251. * A hook that is run after upserting
  252. * @param {string} name
  253. * @param {Function} fn A callback function that is called with the result of upsert(), options
  254. * @name afterUpsert
  255. * @memberof Sequelize.Model
  256. */
  257. /**
  258. * A hook that is run after creating or updating a single instance, It proxies `afterCreate` and `afterUpdate`
  259. * @param {string} name
  260. * @param {Function} fn A callback function that is called with attributes, options
  261. * @name afterSave
  262. * @memberof Sequelize.Model
  263. */
  264. /**
  265. * A hook that is run before destroying a single instance
  266. * @param {string} name
  267. * @param {Function} fn A callback function that is called with instance, options
  268. *
  269. * @name beforeDestroy
  270. * @memberof Sequelize.Model
  271. */
  272. /**
  273. * A hook that is run after destroying a single instance
  274. * @param {string} name
  275. * @param {Function} fn A callback function that is called with instance, options
  276. *
  277. * @name afterDestroy
  278. * @memberof Sequelize.Model
  279. */
  280. /**
  281. * A hook that is run before restoring a single instance
  282. * @param {string} name
  283. * @param {Function} fn A callback function that is called with instance, options
  284. *
  285. * @name beforeRestore
  286. * @memberof Sequelize.Model
  287. */
  288. /**
  289. * A hook that is run after restoring a single instance
  290. * @param {string} name
  291. * @param {Function} fn A callback function that is called with instance, options
  292. *
  293. * @name afterRestore
  294. * @memberof Sequelize.Model
  295. */
  296. /**
  297. * A hook that is run before updating a single instance
  298. * @param {string} name
  299. * @param {Function} fn A callback function that is called with instance, options
  300. * @name beforeUpdate
  301. * @memberof Sequelize.Model
  302. */
  303. /**
  304. * A hook that is run after updating a single instance
  305. * @param {string} name
  306. * @param {Function} fn A callback function that is called with instance, options
  307. * @name afterUpdate
  308. * @memberof Sequelize.Model
  309. */
  310. /**
  311. * A hook that is run before creating instances in bulk
  312. * @param {string} name
  313. * @param {Function} fn A callback function that is called with instances, options
  314. * @name beforeBulkCreate
  315. * @memberof Sequelize.Model
  316. */
  317. /**
  318. * A hook that is run after creating instances in bulk
  319. * @param {string} name
  320. * @param {Function} fn A callback function that is called with instances, options
  321. * @name afterBulkCreate
  322. * @memberof Sequelize.Model
  323. */
  324. /**
  325. * A hook that is run before destroying instances in bulk
  326. * @param {string} name
  327. * @param {Function} fn A callback function that is called with options
  328. *
  329. * @name beforeBulkDestroy
  330. * @memberof Sequelize.Model
  331. */
  332. /**
  333. * A hook that is run after destroying instances in bulk
  334. * @param {string} name
  335. * @param {Function} fn A callback function that is called with options
  336. *
  337. * @name afterBulkDestroy
  338. * @memberof Sequelize.Model
  339. */
  340. /**
  341. * A hook that is run before restoring instances in bulk
  342. * @param {string} name
  343. * @param {Function} fn A callback function that is called with options
  344. *
  345. * @name beforeBulkRestore
  346. * @memberof Sequelize.Model
  347. */
  348. /**
  349. * A hook that is run after restoring instances in bulk
  350. * @param {string} name
  351. * @param {Function} fn A callback function that is called with options
  352. *
  353. * @name afterBulkRestore
  354. * @memberof Sequelize.Model
  355. */
  356. /**
  357. * A hook that is run before updating instances in bulk
  358. * @param {string} name
  359. * @param {Function} fn A callback function that is called with options
  360. * @name beforeBulkUpdate
  361. * @memberof Sequelize.Model
  362. */
  363. /**
  364. * A hook that is run after updating instances in bulk
  365. * @param {string} name
  366. * @param {Function} fn A callback function that is called with options
  367. * @name afterBulkUpdate
  368. * @memberof Sequelize.Model
  369. */
  370. /**
  371. * A hook that is run before a find (select) query
  372. * @param {string} name
  373. * @param {Function} fn A callback function that is called with options
  374. * @name beforeFind
  375. * @memberof Sequelize.Model
  376. */
  377. /**
  378. * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
  379. * @param {string} name
  380. * @param {Function} fn A callback function that is called with options
  381. * @name beforeFindAfterExpandIncludeAll
  382. * @memberof Sequelize.Model
  383. */
  384. /**
  385. * A hook that is run before a find (select) query, after all option parsing is complete
  386. * @param {string} name
  387. * @param {Function} fn A callback function that is called with options
  388. * @name beforeFindAfterOptions
  389. * @memberof Sequelize.Model
  390. */
  391. /**
  392. * A hook that is run after a find (select) query
  393. * @param {string} name
  394. * @param {Function} fn A callback function that is called with instance(s), options
  395. * @name afterFind
  396. * @memberof Sequelize.Model
  397. */
  398. /**
  399. * A hook that is run before a count query
  400. * @param {string} name
  401. * @param {Function} fn A callback function that is called with options
  402. * @name beforeCount
  403. * @memberof Sequelize.Model
  404. */
  405. /**
  406. * A hook that is run before a define call
  407. * @param {string} name
  408. * @param {Function} fn A callback function that is called with attributes, options
  409. * @name beforeDefine
  410. * @memberof Sequelize
  411. */
  412. /**
  413. * A hook that is run after a define call
  414. * @param {string} name
  415. * @param {Function} fn A callback function that is called with factory
  416. * @name afterDefine
  417. * @memberof Sequelize
  418. */
  419. /**
  420. * A hook that is run before Sequelize() call
  421. * @param {string} name
  422. * @param {Function} fn A callback function that is called with config, options
  423. * @name beforeInit
  424. * @memberof Sequelize
  425. */
  426. /**
  427. * A hook that is run after Sequelize() call
  428. * @param {string} name
  429. * @param {Function} fn A callback function that is called with sequelize
  430. * @name afterInit
  431. * @memberof Sequelize
  432. */
  433. /**
  434. * A hook that is run before a connection is created
  435. * @param {string} name
  436. * @param {Function} fn A callback function that is called with config passed to connection
  437. * @name beforeConnect
  438. * @memberof Sequelize
  439. */
  440. /**
  441. * A hook that is run after a connection is created
  442. * @param {string} name
  443. * @param {Function} fn A callback function that is called with the connection object and the config passed to connection
  444. * @name afterConnect
  445. * @memberof Sequelize
  446. */
  447. /**
  448. * A hook that is run before a connection is disconnected
  449. * @param {string} name
  450. * @param {Function} fn A callback function that is called with the connection object
  451. * @name beforeDisconnect
  452. * @memberof Sequelize
  453. */
  454. /**
  455. * A hook that is run after a connection is disconnected
  456. * @param {string} name
  457. * @param {Function} fn A callback function that is called with the connection object
  458. * @name afterDisconnect
  459. * @memberof Sequelize
  460. */
  461. /**
  462. * A hook that is run before Model.sync call
  463. * @param {string} name
  464. * @param {Function} fn A callback function that is called with options passed to Model.sync
  465. * @name beforeSync
  466. * @memberof Sequelize
  467. */
  468. /**
  469. * A hook that is run after Model.sync call
  470. * @param {string} name
  471. * @param {Function} fn A callback function that is called with options passed to Model.sync
  472. * @name afterSync
  473. * @memberof Sequelize
  474. */
  475. /**
  476. * A hook that is run before sequelize.sync call
  477. * @param {string} name
  478. * @param {Function} fn A callback function that is called with options passed to sequelize.sync
  479. * @name beforeBulkSync
  480. * @memberof Sequelize
  481. */
  482. /**
  483. * A hook that is run after sequelize.sync call
  484. * @param {string} name
  485. * @param {Function} fn A callback function that is called with options passed to sequelize.sync
  486. * @name afterBulkSync
  487. * @memberof Sequelize
  488. */