JSPM

  • Created
  • Published
  • Downloads 52857
  • Score
    100M100P100Q152747F
  • License MIT

A no brainer hooks module for execute before/after lifecycle hooks

Package Exports

  • @poppinss/hooks
  • @poppinss/hooks/build

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@poppinss/hooks) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Hooks

A no brainer module to execute lifecycle hooks in sequence.

circleci-image npm-image license-image

I find myself re-writing the code for hooks in multiple packages, so decided to extract it to it's own module, that can be re-used by other modules of AdonisJs.

Table of contents

How it works?

The hooks class exposes the API to register, remove and exec lifecycle hooks for any number of actions or events. The class API is meant to be used internally by user facing code, so that you can improve the autocomplete UX.

For example: The Lucid models uses this class internally and expose before and after methods on the model itself. Doing this, Lucid can control the autocomplete, type checking for the before and after methods itself, without relying on this package to expose the generics API.

Also generics increases the number of types, Typescript has to generate. So it's better to avoid them whenever possible.

Usage

Install the package from npm registry as follows:

npm i @poppinss/hooks

# yarn
yarn add @poppinss/hooks

and use it as follows

import { Hooks } from '@poppinss/hooks'
const hooks = new Hooks()

hooks.add('before', 'save', function () {
})

// Later invoke before save hooks
await hooks.exec('before', 'save', { id: 1 })

If you want the end user to define IoC container bindings as the hook handler, then you need to pass the Ioc container resolver to the Hooks constructor. Following is the snippet from Lucid models.

import { Ioc } from '@adonisjs/fold'
const ioc = new Ioc()
const resolver = ioc.getResolver(undefined, 'modelHooks', 'App/Models/Hooks')

const hooks = new Hooks(resolver)

The resolver allows the end user to pass the hook reference as string and hooks must live inside App/Models/Hooks folder.

hooks.add('before', 'save', 'User.encryptPassword')

API Docs

Following are the autogenerated files via Typedoc

Maintainers

Harminder virk