Search code examples
javascriptnode.jssails.jswaterline

How to extend the functionality of blueprints in Sails.js without overriding the whole blueprint?


I have a problem to which I haven't been able to find an answer, even though I feel like this kind of a feature is very common in web applications. I'm fairly new to sails.js and web development in general, so feel free to correct me if I'm using wrong terminology or something.

I'm trying to alter the default functionality of sails.js blueprints, specifically 'find' for starters. I have a model, let's call it Book, that has an attribute 'user', which of course relates to a user. I'd like to filter results from localhost:[port]/book so that it only showed the books whose owner is the currently logged in user instead of showing all the books in the database.

So far I've tried checking out if policies would be the answer, but it seems like they produce very binary 'yes/no' results and can't be used for filtering. Then I tried overriding the default find action from the BookController, which kind of works, but I'm afraid I'm overriding some useful functionality since I don't fully understand the source code for the blueprints. Then I checked out the answer Adding missing request parameter before persistance in Sails.JS, and tried to add the owner as an URL query parameter, but found out I couldn't access the currently logged in user from routes.js and the idea was probably doomed from the start anyway.

Anyway, I was wondering if there was a smart way of handling this issue.


Solution

  • You can set a parameter inside your policies. Create a policy that runs on bookController.find and have it add the user id

    Example (depends on your setup)

    req.options.where.user = req.session.userId
    

    Then when your blueprint runs, it will merge that userid with the other query attributes are passed in the params.

    This is a starter example. You can expand this method to auto attach a user as well on create and update

    config/policies.js

    module.exports.policies = {'book.find':'attachUser'}
    

    api/policies/attachUser.js

    module.exports = function(req, res, next) {
        if(!req.options.where) req.options.where = {};
        req.options.where.user = req.session.userId
    }