Search code examples
javascriptmongoosefeathersjs

Customize cli-generated feathersjs services


I'm writing an api to try featherjs with its mongoose adapter. I want my GET /books/ endpoint to only return books with the private attribute set to false. Should I use a before hook? If that's the case, how do I prevent users from running custom queries in my endpoint? Should I manually empty the params object?


Solution

  • You need to create a before hook in books.hooks.js

    const books_qry = require('../../hooks/books_qry');
    
    module.exports = {
      before: {
       all: [],
       find: [books_qry()],
       ...
    

    Create /src/hooks/books_qry.js

    module.exports = function () {
      return function (context) {
         //You have 2 choices to change the context.params.query
    
         //overwrite any request for a custom query
         context.params.query =  { private: false };
    
         //or add a query param to the request for a custom query
         context.params.query.private = false
    
         //check the updated context.params.query 
         console.log(context.params.query); 
    
         return context;
      }
    }
    

    Select one of the choices that you need. Since I never used mongoose at the moment, check the documentation in order to create a valid query (btw above example works for mongodb adapter)