Search code examples
feathersjs

Featherjs - Add custom field to hook context object


When using feathersjs on both client and server side, in the app hooks (in the client) we receive an object with several fields, like the service, the method, path, etc.

I would like, with socket io, to add a custom field to that object. Would that the possible? To be more precise, I would like to send to the client the current version of the frontend app, to be able to force or suggest a refresh when the frontend is outdated (using pwa).

Thanks!


Solution

  • For security reasons, only params.query and data (for create, update and patch) are passed between the client and the server. Query parameters can be pulled from the query into the context with a simple hook like this (where you can pass the version as the __v query parameter):

    const setVersion = context => {
      const { __v, ...query } = context.params.query || {};
    
      context.version = __v;
      // Update `query` with the data without the __v parameter
      context.params.query = query;
    
      return context;
    }
    

    Additionally you can also add additional parameters like the version number as extraHeaders which are then available as params.headers.

    Going the other way around (sending the version information from the server) can be done by modifying context.result in an application hook:

    const { version } = require('package.json');
    
    app.hooks({
      after: {
        all (context) {
          context.result = {
            ...context.result,
            __v: version
          }
        }
      }
    });
    

    It needs to be added to the returned data since websockets do not have any response headers.