API

Usage

Use feathers-hooks-common v4.x.x with FeathersJS Buzzard.

Use feathers-hooks-common v3.10.0 with FeathersJS Auk. v4.x.x. should also work if you don’t use callbacks in your hooks.

Hooks may be used on the client as well as the server.

npm install --save feathers-hooks-common
// project/src/services/posts/posts.hooks.js
const { disableMultiItemChange, fastJoin } = require('feathers-hooks-common');
const postResolvers = {
joins: {
author: () => async post => post.author = (await users.find({ query: {
id: post.userId
} }))[0],
starers: $select => async post => post.starers = await users.find({ query: {
id: { $in: post.starIds }, $select: $select || ['name']
} }),
}
};
module.exports = {
before: {
patch: [ disableMultiItemChange() ],
remove: [ disableMultiItemChange() ]
},
after: {
all: [ fastJoin(postResolvers) ],
},
};

New Features in Buzzard

Features added since the initial Buzzard release are listed in the What’s New section.

These features are new in the Buzzard version.

Migrating from Auk to Buzzard

These changes may affect your projects when you switch from this repo’s last Feathers Auk version (v3.10.0) to its first Feathers Buzzard version (v4.0.0).

Find Hooks using Tags

Each Feathers hook and utility function is listed under all the tags relevant to it.

Client/server

Coding

Conditionals

Data and Results

Dot notation

Imperative API

MongoDB specific

Performance

Predicates

Query object

REST

Relations

Service methods

Services

Transport

Validation

Hooks

actOnDefault( …hooks )

Runs a series of hooks which mutate context.data or content.result (the Feathers default).
before after methods multi recs guide details tags
yes yes all yes source Coding, Conditionals, Data and Results
Argument Type Default Description
hooks ...Function The hooks to run. They will mutate context.data for before hooks, or context.result for after hooks. This is the default action for hooks.

actOnDispatch( …hooks )

Runs a series of hooks which mutate context.dispatch.
before after methods multi recs guide details tags
yes yes all yes source Coding, Conditionals, Data and Results
Argument Type Default Description
hooks ...Function The hooks to run. They will mutate context.dispatch.

alterItems( func )

Make changes to data or result items. Very flexible.
before after methods multi recs guide details tags
yes yes all yes source Coding, Conditionals, Data and Results, Imperative API, Predicates, Relations
Argument Type Default Description
func Function (item, context) => {} Function modifies item in place. See below.
Name Type Description
result undefined || item The mutated item. Returning undefined means the item in the parameters was mutated in place.
Argument Type Description
item Object The item. The function modifies it in place.
context Object The current context. It contains any alterations made to items so far.

cache(cacheMap [, keyField] [, options ])

Persistent, least-recently-used record cache for services.
before after methods multi recs guide details tags
yes yes all yes source Data and Results, Performance, Services
Argument Type Default Description
cacheMap Object Map Instance of Map, or an object with a similar API, to be used as the cache.
keyField String context.service.id or item._id ? '_id' !! 'id' The name of the record id field.
option Object Options.
options Argument Type Default Description
clone Function item => JSON.parse( JSON.stringify(item) ) Function to perform a deep clone. See below.

The cache hook must be registered in both before and after.

The cache will grow without limit when Map is used and the resulting memory pressure may adversely affect your performance. Map should only be used when you know or can control its size.

Argument Type Default Description
item Object The record.
clonedItem Object A clone of item.

debug( label [, …fieldNames ] )

Display the current hook context for debugging.
before after methods multi recs guide details tags
yes yes all yes source Coding
Argument Type Default Description
label String Label to identify the logged information.
fieldNames dot notation The field values in context.params to display.

dePopulate( )

Remove records and properties created by the populate hook.
before after methods multi recs guide details tags
yes yes all yes source Relations

disableMultiItemChange( )

Prevents null from being used as an id in patch and remove service methods.
before after methods multi recs guide details tags
yes no update, patch, remove yes source Service methods

disableMultiItemCreate( )

Prevents multi-item creates.
before after methods multi recs guide details tags
yes no create yes source Service methods

disablePagination()

Disables pagination when query.$limit is -1 or '-1'.
before after methods multi recs guide details tags
yes no find yes source Data and Results, Service methods

disallow( …transports )

Prevents access to a service method completely or for specific transports.
before after methods multi recs guide details tags
yes yes all yes source Service methods
Argument Type Default Description
transports Array< String > disallow all transports The transports that you want to disallow.
transports Value Description
socketio allow calls by Socket.IO transport
primus allow calls by Primus transport
rest allow calls by REST transport
external allow calls other than from server
server allow calls from server

discard( …fieldNames )

Delete certain fields from the record(s).
before after methods multi recs guide details tags
yes create, update, patch yes source Data and Results
yes all

The discard hook will remove fields even if the service is being called from the server. You may want to condition the hook to run only for external transports, e.g. iff(isProvider('external'), discard(...)).

Name Type Description
fieldNames dot notation One or more fields you want to remove from the record(s).

discardQuery( …fieldNames )

Delete certain fields from the query object.
before after methods multi recs guide details tags
yes no all yes source Query object

The keep hook will remove any fields not specified even if the service is being called from the server. You may want to condition the hook to run only for external transports, e.g. iff(isProvider('external'), discardQuery(...)).

Name Type Description
fieldNames dot notation One or more fields you want to remove from the query.

every( …predicates )

Return the and of a series of sync or async predicate functions.
before after methods multi recs guide details tags
yes yes all yes source Conditionals, Predicates
Argument Type Default Description
predicates Array< Function > Functions which take the current hook as a param and return a boolean result.
Name Type Description
result Boolean The logical and of predicates

fastJoin( schema [, query] )

Join related records. It's very fast.
before after methods multi recs guide details tags
yes yes all yes fastJoin source Imperative API, Performance, Relations

fastJoin is preferred over using populate.

Argument Type Default Description
resolvers Object or context => Object The group of operations to perform on the data.
query Object run all resolvers with undefined params You can customise the current operations with the optional query.
resolvers Argument Type Default Description
before context => { } Processing performed before the operations are started. Batch-loaders are usually created here.
after context => { } Processing performed after all other operations are completed.
joins Object Resolver functions provide a mapping between a portion of a operation and actual backend code responsible for handling it.

Read the guide for more information on the arguments.

Using number of service calls
populate 22
fastJoin alone 2
fastJoin and cache 0

The cache hook also makes get service calls more efficient.

The cache hook must be registered in both before and after.

iff( predicate, …hookFuncsTrue ).else( …hookFuncsFalse )

Execute one or another series of hooks depending on a sync or async predicate.
before after methods multi recs guide details tags
yes yes all yes source Conditionals
Argument Type Default Description
predicate Boolean, Promise or Function Determine if hookFuncsTrue or hookFuncsFalse should be run. If a function, predicate is called with the context as its param. It returns either a boolean or a Promise that evaluates to a boolean.
hookFuncsTrue Array< Function > Sync or async hook functions to run if true. They may include other conditional hooks.
hookFuncsTrue Array< Function > Sync or async hook functions to run if false. They may include other conditional hooks.

iffElse( predicate, hookFuncsTrue, hookFuncsFalse )

Execute one array of hooks or another based on a sync or async predicate.
before after methods multi recs guide details tags
yes yes all yes source Conditionals
Argument Type Default Description
predicate Boolean, Promise or Function Determine if hookFuncsTrue or hookFuncsFalse should be run. If a function, predicate is called with the context as its param. It returns either a boolean or a Promise that evaluates to a boolean.
hookFuncsTrue Array< Function > Sync or async hook functions to run if true. They may include other conditional hooks.
hookFuncsTrue Array< Function > Sync or async hook functions to run if false. They may include other conditional hooks.

isNot( predicate )

Negate a sync or async predicate function.
before after methods multi recs guide details tags
yes yes all yes source Conditionals, Predicates
Argument Type Default Description
predicate Function Boolean A sync or async function which take the current hook as a param and returns a boolean result.
Name Type Description
result Boolean The not of predicate

isProvider( …transports )

Check which transport provided the service call.
before after methods multi recs guide details tags
yes yes all yes source Conditionals, Predicates, Services, Transport
Name Type Default Description
transports Array< String > The transports you want to allow.
transports Value Description
socketio Allow calls by Socket.IO transport.
primus Allow calls by Primus transport.
rest Allow calls by REST transport.
external Allow calls other than from server.
server Allow calls from server.
Name Type Description
result Boolean If the call was made by one of the transports.

keep( …fieldNames )

Keep certain fields in the record(s), deleting the rest.
before after methods multi recs guide details tags
yes create, update, patch yes source Data and Results
yes all

The keep hook will remove any fields not specified even if the service is being called from the server. You may want to condition the hook to run only for external transports, e.g. iff(isProvider('external'), keep(...)).

Name Type Description
fieldNames dot notation The only fields you want to keep in the record(s).

keepQuery( …fieldNames )

Keep certain fields in the query object, deleting the rest.
before after methods multi recs guide details tags
yes yes all yes source Query object

The keepQuery hook will remove any fields not specified even if the service is being called from the server. You may want to condition the hook to run only for external transports, e.g. iff(isProvider('external'), keepQuery(...)).

Name Type Description
fieldNames dot notation The only fields you want to keep in the query object.

lowerCase( … fieldNames )

Convert certain field values to lower case.
before after methods multi recs guide details tags
yes create, update, patch yes source Data and Results
yes all
Name Type Description
fieldNames dot notation The fields in the record(s) whose values are converted to lower case.

mongoKeys(ObjectID, keys)

Wrap MongoDB foreign keys in ObjectID.
before after methods multi recs guide details tags
yes no all yes source Data and Results, MongoDB specific, Relations
Argument Type Default Description
ObjectID Function - require('mongodb').ObjectID or equivalent.
foreignKeyNames Array < String > dot notation allowed - Field names of the foreign keys.

paramsFromClient( …whitelist )

Pass context.params from client to server. Server hook.
before after methods multi recs guide details tags
yes yes all yes source Client/server, Coding, Transport
Argument Type Default Description
whitelist dot notation Names of the props permitted to be in context.params. Other props are ignored. This is a security feature.

populate( options )

Join related records.
before after methods multi recs guide details tags
yes yes all yes populate source Relations

fastJoin is preferred over using populate.

Argument Type Default Description
options Object Options.
schema Object Function (context, options) => {} Info on how to join records.
checkPermissions Function no permission check Check if call allowed joins.
profile Boolean false If profile info is to be gathered.
schema Argument Type Default Description
service String The name of the service providing the items, actually its path.
nameAs dot notation service Where to place the items from the join
parentField dot notation The name of the field in the parent item for the relation.
childField dot notation if database supports it The name of the field in the child item for the relation. Dot notation is allowed and will result in a query like { 'name.first': 'John' } which is not suitable for all DBs. You may use query or select to create a query suitable for your DB.
permissions any no permission check Who is allowed to perform this join. See checkPermissions above.
query Object An object to inject into context.params.query.
select Function (context, parentItem, depth) => {} A function whose result is injected into the query.
asArray Boolean false Force a single joined item to be stored as an array.
paginate Boolean Number false Controls pagination for this service.
useInnerPopulate Boolean false Perform any populate or fastJoin registered on this service.
provider undefined Call the service as the server, not with the client’s transport.
include Array< Object > or Object Continue recursively join records to these records.

Read the guide for more information on the arguments.

preventChanges( ifThrow, …fieldNames )

Prevent patch service calls from changing certain fields.
before after methods multi recs guide details tags
yes no patch yes source Data and Results, Service methods
Argument Type Default Description
ifThrow Boolean Deletes any fieldNames if false; throws if true.
fieldNames dot notation The fields names which may not be patched.

required(…fieldNames)

Check selected fields exist and are not falsey. Numeric 0 is acceptable.
before after methods multi recs guide details tags
yes no create, update, patch yes source Data and Results, Services, Validation
Name Type Description
fieldNames dot notation These fields must exist and not be falsey. Numeric 0 is acceptable.

runParallel( hookFunc, clone [, depth ] )

Run a hook in parallel to the other hooks and the service call.
before after methods multi recs guide details tags
yes yes all yes source Client/server, Data and Results, Performance, Services
Argument Type Default Description
hookFunc Function The hook function to run in parallel to the rest of the service call.
clone Function Function to deep clone its only parameter.
depth Number 6 Depth to which context is to be cloned. 0 does not clone. A depth of 5 would clone context.result.data.[].item.

serialize( schema )

Prune values from related records. Calculate new values.
before after methods multi recs guide details tags
yes yes all yes source Relations
Argument Type Default Description
schema Object Function context => schema How to serialize the items.
schema Argument Type Default Description
only Array< String> or String The names of the fields to keep in each item. The names for included sets of items plus _include and _elapsed are not removed by only.
exclude Array< String> or String The names of fields to drop in each item. You may drop, at your own risk, names of included sets of items, _include and _elapsed.
computed Object The new names you want added and how to compute their values.
schema .computed Argument Type Default Description
fieldName String The name of the field to add to the records.
computeFunnc Function (record, context) => value Function to calculate the computed value. item: The item with all its initial values, plus all of its included items. The function can still reference values which will be later removed by only and exclude. context: The context passed to serialize.

setNow( …fieldNames )

Create/update certain fields to the current date-time.
before after methods multi recs guide details tags
yes yes all yes source Data and Results
Name Type Description
fieldNames dot notation The fields that you want to add or set to the current date-time.

setSlug( slug [, fieldName] )

Fix slugs in URL, e.g. /stores/:storeId.
before after methods multi recs guide details tags
yes yes all yes source REST, Transport
Argument Type Default Description
slug String The slug as it appears in the route, e.g. storeId for/stores/:storeId/candies.
fieldName String query[slug] The field to contain the slug value.
transport hook.data .storeId hook.params .query code run on client
socketio undefined { size: 'large', storeId: '123' } candies.create({ name: 'Gummi',qty: 100 }, { query: { size: 'large', storeId: '123' } })
rest :storeId same as above same as above
raw HTTP 123 { size: 'large' } fetch('/stores/123/candies?size=large', ..

This hook normalizes the difference between the transports.

sifter( siftFunc )

Filter data or result records using a MongoDB-like selection syntax.
before after methods multi recs guide details tags
no yes find yes source Data and Results, Relations, Service methods, Services
Argument Type Default Description
siftFunc Function Function similar to context => sift(mongoQueryObj). Information about the mongoQueryObj syntax is available at crcn/sift.
const sift = require('sift');
const { sifter } = require('feathers-hooks-common');
const selectCountry = country => () => sift({ address : { country: country } });
module.exports = { before: {
find: sifter(selectCountry('Canada')),
} };

skipRemainingHooks( predicate )

Conditionally skip running all remaining hooks.
before after methods multi recs guide details tags
yes yes all yes source Conditionals, Data and Results, Services

The database call itself will be shipped only if context.result has been set.

Argument Type Default Description
predicate Function, Boolean content => content.result A predicate. If true the remaining hooks are skipped. The default checks if context.result has been set.

softDelete( fieldName )

Flag records as logically deleted instead of physically removing them.
before after methods multi recs guide details tags
yes no all yes source Services

Must be registered on all the call types: create, get, update, patch, remove and find.

Argument Type Default Description
fieldName String 'deleted' The name of the field for the logically deleted flag.

The user record is read by feathers-authenticationwith aget. ThesoftDelete` hook will be run for this call unless it is conditioned to ignore it. This situation raises the most issues for this hook.

some( …predicates )

Return the or of a series of sync or async predicate functions.
before after methods multi recs guide details tags
yes yes all yes source Conditionals, Predicates
Argument Type Default Description
predicates Array< Function > Functions which take the current hook as a param and return a boolean result.
Name Type Description
result Boolean The logical or of predicates

stashBefore( fieldName )

Stash current value of record, usually before mutating it. Performs a get call.
before after methods multi recs guide details tags
yes no get, update, patch, remove yes source Data and Results, Services
Argument Type Default Description
fieldName 'before' The name of the context.params property to contain the current record value.

traverse( transformer [, getObject] )

Transform fields & objects in place in the record(s) using a recursive walk. Powerful.
before after methods multi recs guide details tags
yes yes all yes source Data and Results, Imperative API, Query object, REST
Argument Type Default Description
transformer Function Called for every node in every record(s). May change the node in place.
getObject Function context.data or context.result[.data] Function with signature context => {} which returns the object to traverse.

unless( predicate, …hookFuncs )

Execute a series of hooks if a sync or async predicate is falsey.
before after methods multi recs guide details tags
yes yes all yes source Conditionals
Argument Type Default Description
predicate Boolean, Promise or Function Run hookFunc if the predicate is false. If a function, predicate is called with the context as its param. It returns either a boolean or a Promise that evaluates to a boolean.
hookFuncs Array< Function > Sync or async hook functions to run if true. They may include other conditional hooks.

validate( validator )

Validate data using a validation function.
before after methods multi recs guide details tags
yes no create, update, patch yes validate source Data and Results, Services, Validation
Argument Type Default Description
validator Function Validation function. See Details below..
Argument Type Default Description
formValues Object The data, e.g. { name: 'John', ... }
context Object The hook context.
errors Object null An error object like { fieldName1: 'message', ... }

Promise functions should throw on an error or reject with new errors.BadRequest('Error message', { errors: { fieldName1: 'message', ... } });. Their .then returns either sanitized values to replace the data in the context, or null.

If you have a different signature for the validator then pass a wrapper as the validator e.g. values => myValidator(..., values, ...).

Wrap your validator in Node’s util.promisify if it uses a callback.

validateSchema( schema, ajv [, options] )

Validate data using JSON-Schema.
before after methods multi recs guide details tags
yes yes all yes source Data and Results, Services, Validation
Argument Type Default Description
schema Object The JSON-schema.
ajv Function Object The ajv validator. Could be either the Ajv constructor or an instance of it.
options Object Options for validateSchema and ajv.
options Argument Type Default Description
addNewError Function see below Custom error message formatter.
other any Any ajv options. Only effective when the second parameter is the Ajv constructor.
Argument Type Default Description
currentFormattedMessages any initially null Formatted messages so far. Initially null.
ajvErrorObject Object ajv error object
itemsLen Number How many data items there are. 1-based.
item Number Which item this is. 0-based.
newFormattedMessages any The function returns the updated formatted messages.

error.errors will, by default, contain an array of error messages. By default the message will look like

[ "'in row 1 of 3, first' should match format \"startWithJo\"",
"in row 1 of 3, should have required property 'last'",
"'in row 2 of 3, first' should match format \"startWithJo\"",
"in row 3 of 3, should have required property 'last'" ]

You could, for example, return { name1: message, name2: message } which might be more suitable for a UI.

when( predicate, …hookFuncs )

An alias for iff.

Utilities

checkContext( context [, type ] [, methods ] [, label ] )

Restrict a hook to run for certain methods and method types. (Utility function.)
guide details tags
source Coding, Services
Argument Type Default Description
context Object The hook context.
type String all types The service type allowed - before, after.
methods Array< String > all methods The service methods allowed - find, get, update, patch, remove.
label String 'anonymous' Name of hook to use with throw.

combine( …hookFuncs )

Sequentially execute multiple sync or async hooks.
before after methods multi recs guide details tags
yes yes all n/a source Coding, Conditionals
Argument Type Default Description
hookFuncs Array<Function > Hooks, used the same way as when you register them.

deleteByDot( obj, path )

Deletes a property from an object using dot notation, e.g. address.city. (Utility function.)
guide details tags
source Coding, Dot notation
Argument Type Default Description
obj Object The object.
path String The path to the property, e.g. address.city.

existsByDot( obj, path )

Check if a property exists in an object by using dot notation, e.g. address.city. (Utility function.)
guide details tags
source Coding, Dot notation
Argument Type Default Description
obj Object The object.
path String The path to the property, e.g. address.city.
Name Type Description
result Boolean If a property exists at path.

getByDot( obj, path )

Return a property value from an object using dot notation, e.g. address.city. (Utility function.)
guide details tags
source Coding, Dot notation
Argument Type Default Description
obj Object The object.
path String The path to the property, e.g. address.city.
Name Type Description
result any The property value.

setByDot( obj, path, value )

Set a property value in an object using dot notation, e.g. address.city. (Utility function.)
guide details tags
source Coding, Dot notation
Argument Type Default Description
obj Object The object.
path String The path to the property, e.g. address.city.
value any The value to set the property to.

getItems( context )

Get the records in context.data or context.result[.data]. (Utility function.)
guide details tags
source Coding, Data and Results
Argument Type Default Description
context Object The hook context.
Name Type Description
records Array< Object > | Object | undefined The records.

replaceItems( context, records )

Replace the records in context.data or context.result[.data]. (Utility function.)
guide details tags
source Coding, Data and Results
Argument Type Default Description
context Object The hook context.
records Array< Object > Object The new records.

makeCallingParams( context, query, include, inject )

Build context.params for service calls. (Utility function.)
guide details tags
source Coding, Services
Argument Type Default Description
context Object The existing hook context.
query Object The context.params.query for the new context.
include Object The names of the props in context to include in the new context.
inject Object Additional props to add to the new context.
newContext Object The new context created
Variable Type Default Description
newContext Object The new context created.

paramsForServer( params [, … whitelist] )

Pass an explicit context.params from client to server. Client-side. (Utility function.)
guide details tags
source Client/server, Coding, Transport
Argument Type Default Description
params Object The context.params to use for the service call, including any query object.
whitelist dot notation all props in context.params Names of the props in context.params to transfer to the server. This is a security feature. All props are transferred if no whitelist is provided.

runHook( [ hookContext ] )( hookFunc )

Let's you call a hook right after the service call. (Utility function.)
guide details tags
source Coding, Services
Argument Type Default Description
hookContext Object {} The context for hookFunc.
hookFunc Function The hook to run.

???

?????????? hook ??? not defined.
Argument Type Default Description
transports
?????????? hook ??? not defined.

F.A.Q.

Coerce data types

A common need is converting fields coming in from query params. These fields are provided as string values by default and you may need them as numbers, booleans, etc.

The validateSchema does a wide selection of type coercions, as well as checking for missing and unexpected fields.

What’s New

The details are at Changelog.

Feb. 2018

March 2018