Search code examples
hookfeathersjspluck

How does pluck hook work in feathersjs


In the feathersjs docs the explanation provided is as follows:

pluck discards all fields except for the specified ones, either from the data submitted or from the result. If the data is an array or a paginated find result the hook will remove the field(s) for every item.

import _pluck from '../common/_pluck'; 
import checkContextIf from './check-context-if'; 
import getItems from './get-items'; 
import replaceItems from './replace-items'; 

export default function (...fieldNames) { 
  return context => { 
    checkContextIf(context, 'before', ['create', 'update', 'patch'], 'pluck'); 
    if(context.params.provider) { 
      replaceItems(context, _pluck(getItems(context), fieldNames)); 
    } 

    return context; 
  }; 
} 

The getItems utility returns the items in either hook.data or hook.result depending on whether the hook is being used as a before or after hook. hook.result.data or hook.result is returned for a find method.

The returned items are always an array to simplify further processing.

The replaceItems utility is the reverse of getItems , returning the items where they came from.

My question relates to the checkContextIf function. This function prevents the pluck hook from being called except before the create,update and patch methods. How then does the pluck hook work on the results of the query. Are not the results produced after the service call and handled in an after hook?


Solution

  • As the documentation states:

    The getItems utility returns the items in either hook.data or hook.result depending on whether the hook is being used as a before or after hook.

    hook.data is the data (body) sent with a create, patch or update request so it can be used to omit fields that you do not want to be saved to the database. This is also documented in the hooks API:

    • data - The request data (for create, update and patch)