🎁 Custom Handlers for FeathersJS Events
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:
- Control the default behavior of the event by returning a boolean.
- For
created
,patched
, andupdated
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.
- Perform side effects using the current service
model
or with othermodels
. Themodels
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 serverutils
: an object containing the following propertiesmodel
The current service's Model class.models
The same as the$FeathersVuex
object, gives you access to each api with their respective model classes.