Simple email application for Android. Original source code: https://framagit.org/dystopia-project/simple-email
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

444 lines
9.6 KiB

  1. # before-after-hook
  2. > asynchronous hooks for internal functionality
  3. [![Build Status](https://travis-ci.org/gr2m/before-after-hook.svg?branch=master)](https://travis-ci.org/gr2m/before-after-hook)
  4. [![Coverage Status](https://coveralls.io/repos/gr2m/before-after-hook/badge.svg?branch=master)](https://coveralls.io/r/gr2m/before-after-hook?branch=master)
  5. [![Greenkeeper badge](https://badges.greenkeeper.io/gr2m/before-after-hook.svg)](https://greenkeeper.io/)
  6. ## Usage
  7. ```js
  8. // instantiate hook API
  9. const hook = new Hook()
  10. // Create a hook
  11. function getData (options) {
  12. return hook('get', options, fetchFromDatabase)
  13. .then(handleData)
  14. .catch(handleGetError)
  15. }
  16. // register before/error/after hooks.
  17. // The methods can be async or return a promise
  18. hook.before('get', beforeHook)
  19. hook.error('get', errorHook)
  20. hook.after('get', afterHook)
  21. getData({id: 123})
  22. ```
  23. The methods are executed in the following order
  24. 1. `beforeHook`
  25. 2. `fetchFromDatabase`
  26. 3. `afterHook`
  27. 4. `getData`
  28. `beforeHook` can mutate `options` before it’s passed to `fetchFromDatabase`.
  29. If an error is thrown in `beforeHook` or `fetchFromDatabase` then `errorHook` is
  30. called next.
  31. If `afterHook` throws an error then `handleGetError` is called instead
  32. of `getData`.
  33. If `errorHook` throws an error then `handleGetError` is called next, otherwise
  34. `afterHook` and `getData`.
  35. You can also use `hook.wrap` to achieve the same thing as shown above:
  36. ```js
  37. hook.wrap('get', async (getData, options) => {
  38. await beforeHook(options)
  39. try {
  40. const result = getData(options)
  41. } catch (error) {
  42. await errorHook(error, options)
  43. }
  44. await afterHook(result, options)
  45. })
  46. ```
  47. ## Install
  48. ```
  49. npm install before-after-hook
  50. ```
  51. Or download [the latest `before-after-hook.min.js`](https://github.com/gr2m/before-after-hook/releases/latest).
  52. ## API
  53. - [Constructor](#constructor)
  54. - [hook.api](#hookapi)
  55. - [hook()](#hook)
  56. - [hook.before()](#hookbefore)
  57. - [hook.error()](#hookerror)
  58. - [hook.after()](#hookafter)
  59. - [hook.wrap()](#hookwrap)
  60. - [hook.remove()](#hookremove)
  61. ### Constructor
  62. The `Hook` constructor has no options and returns a `hook` instance with the
  63. methods below
  64. ```js
  65. const hook = new Hook()
  66. ```
  67. ### hook.api
  68. Use the `api` property to return the public API:
  69. - [hook.before()](#hookbefore)
  70. - [hook.after()](#hookafter)
  71. - [hook.error()](#hookerror)
  72. - [hook.wrap()](#hookwrap)
  73. - [hook.remove()](#hookremove)
  74. That way you don’t need to expose the [hook()](#hook) method to consumers of your library
  75. ### hook()
  76. Invoke before and after hooks. Returns a promise.
  77. ```js
  78. hook(nameOrNames, [options,] method)
  79. ```
  80. <table>
  81. <thead>
  82. <tr>
  83. <th>Argument</th>
  84. <th>Type</th>
  85. <th>Description</th>
  86. <th>Required</th>
  87. </tr>
  88. </thead>
  89. <tr>
  90. <th align="left"><code>name</code></th>
  91. <td>String or Array of Strings</td>
  92. <td>Hook name, for example <code>'save'</code>. Or an array of names, see example below.</td>
  93. <td>Yes</td>
  94. </tr>
  95. <tr>
  96. <th align="left"><code>options</code></th>
  97. <td>Object</td>
  98. <td>Will be passed to all before hooks as reference, so they can mutate it</td>
  99. <td>No, defaults to empty object (<code>{}</code>)</td>
  100. </tr>
  101. <tr>
  102. <th align="left"><code>method</code></th>
  103. <td>Function</td>
  104. <td>Callback to be executed after all before hooks finished execution successfully. <code>options</code> is passed as first argument</td>
  105. <td>Yes</td>
  106. </tr>
  107. </table>
  108. Resolves with whatever `method` returns or resolves with.
  109. Rejects with error that is thrown or rejected with by
  110. 1. Any of the before hooks, whichever rejects / throws first
  111. 2. `method`
  112. 3. Any of the after hooks, whichever rejects / throws first
  113. Simple Example
  114. ```js
  115. hook('save', record, function (record) {
  116. return store.save(record)
  117. })
  118. // shorter: hook('save', record, store.save)
  119. hook.before('save', function addTimestamps (record) {
  120. const now = new Date().toISOString()
  121. if (record.createdAt) {
  122. record.updatedAt = now
  123. } else {
  124. record.createdAt = now
  125. }
  126. })
  127. ```
  128. Example defining multiple hooks at once.
  129. ```js
  130. hook(['add', 'save'], record, function (record) {
  131. return store.save(record)
  132. })
  133. hook.before('add', function addTimestamps (record) {
  134. if (!record.type) {
  135. throw new Error('type property is required')
  136. }
  137. })
  138. hook.before('save', function addTimestamps (record) {
  139. if (!record.type) {
  140. throw new Error('type property is required')
  141. }
  142. })
  143. ```
  144. Defining multiple hooks is helpful if you have similar methods for which you want to define separate hooks, but also an additional hook that gets called for all at once. The example above is equal to this:
  145. ```js
  146. hook('add', record, function (record) {
  147. return hook('save', record, function (record) {
  148. return store.save(record)
  149. })
  150. })
  151. ```
  152. ### hook.before()
  153. Add before hook for given name. Returns `hook` instance for chaining.
  154. ```js
  155. hook.before(name, method)
  156. ```
  157. <table>
  158. <thead>
  159. <tr>
  160. <th>Argument</th>
  161. <th>Type</th>
  162. <th>Description</th>
  163. <th>Required</th>
  164. </tr>
  165. </thead>
  166. <tr>
  167. <th align="left"><code>name</code></th>
  168. <td>String</td>
  169. <td>Hook name, for example <code>'save'</code></td>
  170. <td>Yes</td>
  171. </tr>
  172. <tr>
  173. <th align="left"><code>method</code></th>
  174. <td>Function</td>
  175. <td>
  176. Executed before the wrapped method. Called with the hook’s
  177. <code>options</code> argument. Before hooks can mutate the passed options
  178. before they are passed to the wrapped method.
  179. </td>
  180. <td>Yes</td>
  181. </tr>
  182. </table>
  183. Example
  184. ```js
  185. hook.before('save', function validate (record) {
  186. if (!record.name) {
  187. throw new Error('name property is required')
  188. }
  189. })
  190. ```
  191. ### hook.error()
  192. Add error hook for given name. Returns `hook` instance for chaining.
  193. ```js
  194. hook.error(name, method)
  195. ```
  196. <table>
  197. <thead>
  198. <tr>
  199. <th>Argument</th>
  200. <th>Type</th>
  201. <th>Description</th>
  202. <th>Required</th>
  203. </tr>
  204. </thead>
  205. <tr>
  206. <th align="left"><code>name</code></th>
  207. <td>String</td>
  208. <td>Hook name, for example <code>'save'</code></td>
  209. <td>Yes</td>
  210. </tr>
  211. <tr>
  212. <th align="left"><code>method</code></th>
  213. <td>Function</td>
  214. <td>
  215. Executed when an error occurred in either the wrapped method or a
  216. <code>before</code> hook. Called with the thrown <code>error</code>
  217. and the hook’s <code>options</code> argument. The first <code>method</code>
  218. which does not throw an error will set the result that the after hook
  219. methods will receive.
  220. </td>
  221. <td>Yes</td>
  222. </tr>
  223. </table>
  224. Example
  225. ```js
  226. hook.error('save', function (error, options) {
  227. if (error.ignore) return
  228. throw error
  229. })
  230. ```
  231. ### hook.after()
  232. Add after hook for given name. Returns `hook` instance for chaining.
  233. ```js
  234. hook.after(name, method)
  235. ```
  236. <table>
  237. <thead>
  238. <tr>
  239. <th>Argument</th>
  240. <th>Type</th>
  241. <th>Description</th>
  242. <th>Required</th>
  243. </tr>
  244. </thead>
  245. <tr>
  246. <th align="left"><code>name</code></th>
  247. <td>String</td>
  248. <td>Hook name, for example <code>'save'</code></td>
  249. <td>Yes</td>
  250. </tr>
  251. <tr>
  252. <th align="left"><code>method</code></th>
  253. <td>Function</td>
  254. <td>
  255. Executed after wrapped method. Called with what the wrapped method
  256. resolves with the hook’s <code>options</code> argument.
  257. </td>
  258. <td>Yes</td>
  259. </tr>
  260. </table>
  261. Example
  262. ```js
  263. hook.after('save', function (result, options) {
  264. if (result.updatedAt) {
  265. app.emit('update', result)
  266. } else {
  267. app.emit('create', result)
  268. }
  269. })
  270. ```
  271. ### hook.wrap()
  272. Add wrap hook for given name. Returns `hook` instance for chaining.
  273. ```js
  274. hook.wrap(name, method)
  275. ```
  276. <table>
  277. <thead>
  278. <tr>
  279. <th>Argument</th>
  280. <th>Type</th>
  281. <th>Description</th>
  282. <th>Required</th>
  283. </tr>
  284. </thead>
  285. <tr>
  286. <th align="left"><code>name</code></th>
  287. <td>String</td>
  288. <td>Hook name, for example <code>'save'</code></td>
  289. <td>Yes</td>
  290. </tr>
  291. <tr>
  292. <th align="left"><code>method</code></th>
  293. <td>Function</td>
  294. <td>
  295. Receives both the wrapped method and the passed options as arguments so it can add logic before and after the wrapped method, it can handle errors and even replace the wrapped method altogether
  296. </td>
  297. <td>Yes</td>
  298. </tr>
  299. </table>
  300. Example
  301. ```js
  302. hook.wrap('save', async function (saveInDatabase, options) {
  303. if (!record.name) {
  304. throw new Error('name property is required')
  305. }
  306. try {
  307. const result = await saveInDatabase(options)
  308. if (result.updatedAt) {
  309. app.emit('update', result)
  310. } else {
  311. app.emit('create', result)
  312. }
  313. return result
  314. } catch (error) {
  315. if (error.ignore) return
  316. throw error
  317. }
  318. })
  319. ```
  320. See also: [Test mock example](examples/test-mock-example.md)
  321. ### hook.remove()
  322. Removes hook for given name. Returns `hook` instance for chaining.
  323. ```js
  324. hook.remove(name, hookMethod)
  325. ```
  326. <table>
  327. <thead>
  328. <tr>
  329. <th>Argument</th>
  330. <th>Type</th>
  331. <th>Description</th>
  332. <th>Required</th>
  333. </tr>
  334. </thead>
  335. <tr>
  336. <th align="left"><code>name</code></th>
  337. <td>String</td>
  338. <td>Hook name, for example <code>'save'</code></td>
  339. <td>Yes</td>
  340. </tr>
  341. <tr>
  342. <th align="left"><code>beforeHookMethod</code></th>
  343. <td>Function</td>
  344. <td>
  345. Same function that was previously passed to <code>hook.before()</code>, <code>hook.error()</code>, <code>hook.after()</code> or <code>hook.wrap()</code>
  346. </td>
  347. <td>Yes</td>
  348. </tr>
  349. </table>
  350. Example
  351. ```js
  352. hook.remove('save', validateRecord)
  353. ```
  354. ## See also
  355. If `before-after-hook` is not for you, have a look at one of these alternatives:
  356. - https://github.com/keystonejs/grappling-hook
  357. - https://github.com/sebelga/promised-hooks
  358. - https://github.com/bnoguchi/hooks-js
  359. - https://github.com/cb1kenobi/hook-emitter
  360. ## License
  361. [Apache 2.0](LICENSE)