Search code examples
feathersjsfeathers-hook

Remove context.query.params from the service call, but keep it as a URL parameter


I have created a "products" service using feathersjs and mongoose. Here is my service :

// Initializes the `products` service on path `/products`
const createService = require('feathers-mongoose');
const createModel = require('../../models/products.model');
const hooks = require('./products.hooks');

module.exports = function (app) {
  const Model = createModel(app);
  const paginate = app.get('paginate');

  const options = {
    name: 'products',
    Model,
    paginate
  };

  // Initialize our service with any options it requires
  app.use('/products', createService(options));

  // Get our initialized service so that we can register hooks and filters
  const service = app.service('products');

  service.hooks(hooks);
};

My mongoose model include some field like "name", "category" etc. But it doesn't really matter for my problem.

When I call my service like this :

http://localhost:3030/products?lang=fr

As "lang" is not an entry of my database products, I got no result.

Is there a way to remove the "lang" parameter from the query, but to keep it in order to use it in my hook.

I've tried discardQuery, but it will remove the parameter and I can't use it in my hook anymore.

Thanks for your help

SOLUTION

Thanks to daff I have found a solution, in a before hook, I have attached my params.query.lang like this:

context.params.lang = context.params.query.lang;

And right after I discard my context.params.query.lang in order to remove it from the query

commonHooks.discardQuery('lang')

Then I was able in my after hook to get the lang parameter like this :

let lang = context.params.lang;

Solution

  • Why don't you just add it somewhere else, like the context object or context.params before deleting it?

    const { omit } = require('lodash');
    
    app.service('products').hooks({
      before: {
        find(context) {
          context.params.language = context.params.query.language;
    
          context.params.query = omit(context.params.query, 'language');
    
          return context;
        }
      }
    })