hooks.js 15 KB

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