Skip to content

🎁 Custom Handlers for FeathersJS Events

Compare
Choose a tag to compare
@marshallswain marshallswain released this 21 Dec 01:34
· 492 commits to master since this release

As of version 3.1, you can customize the behavior of the event handlers, or even perform side effects based on the event data. This is handled through the new handleEvents option on the service plugin. Here is an example of how you might use this:

handleEvents: {
  created: (item, { model, models }) => {
    // Perform a side effect to remove any record with the same `name`
    const existing = Model.findInStore({ query: { name: item.name }}).data[0]
    if (existing) {
      existing.remove()
    }

    // Perform side effects with other models.
    const { SomeModel } = models.api
    new SomeModel({ /* some custom data */ }).save()

    // Access the store through model.store
    const modelState = model.store.state[model.namespace]
    if (modelState.keyedById[5]) {
      console.log('we accessed the vuex store')
    }

    // If true, the new item will be stored.
    return true
  },
  updated: () => false, // Ignore `updated` events.
  patched: item => item.hasPatchedAttribute && item.isWorthKeeping,
  removed: item => true // The default value, will remove the record from the store
}

As shown above, each handler has two possible uses:

  1. Control the default behavior of the event by returning a boolean.
  • For created, patched, and updated a truthy return will add or update the item in the store.
  • For removed a truthy return will remove the item from the store, if present.
  1. Perform side effects using the current service model or with other models. The models object is the same as the $FeathersVuex object in the Vue plugin.

Each handler receives the following arguments:

  • item: the record sent from the API server
  • utils: an object containing the following properties
    • model The current service's Model class.
    • models The same as the $FeathersVuex object, gives you access to each api with their respective model classes.