是否可以在帆中继承蓝图功能

时间:2014-03-09 09:49:17

标签: node.js sails.js

是否可以重用/调用蓝图功能(find / create / update / destory)并只添加控制器所需的一些项目。如果我很难表达我的问题,我很抱歉,但希望我的例子会有所帮助。

示例:

modue.exports = function(){
    index: ....,
    create: function(req, res){
      try{
        // i want to call the blueprint here to save some things
        create(req, res);
        // then do more after creating the record
        ....
      }catch(err){
       // want to catch some error here like validation err 
       // instead of sending it to   res.serverErr();
      }
    }
    ....
}

2 个答案:

答案 0 :(得分:0)

//File  api/controller/UserController.js

// suppose the model is User under api/models
modue.exports =  {
     create: function(req,res){
        // pass req.query to User Model's Create function, so you dont need to rewrite all
        //optional paramters for this overwrite version 
        User.create(req.query).exec(function(e, r){
           if(e){
               // !!!try to create in a different way!
            }
        })
   }
}

答案 1 :(得分:0)

您需要先从node_modules文件夹中的sails复制blueprint文件夹 将蓝图文件夹粘贴到您的api文件夹中 然后在你的控制器中,例如UserController包括actionUtil,例如

var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

module.exports = {
    create: function (req, res) {
        // paste code from blueprint create.js file
        var Model = actionUtil.parseModel(req);

        // Create data object (monolithic combination of all parameters)
        // Omit the blacklisted params (like JSONP callback param, etc.)
        var data = actionUtil.parseValues(req);


        // Create new instance of model using data from params
        Model.create(data).exec(function created(err, newInstance) {

            // Differentiate between waterline-originated validation errors
            // and serious underlying issues. Respond with badRequest if a
            // validation error is encountered, w/ validation info.
            if (err)
                return res.serverError({status:500, message:'error', err: err});

            // If we have the pubsub hook, use the model class's publish method
            // to notify all subscribers about the created item
            if (req._sails.hooks.pubsub) {
                if (req.isSocket) {
                    Model.subscribe(req, newInstance);
                    Model.introduce(newInstance);
                }
                // Make sure data is JSON-serializable before publishing            
                var publishData = _.isArray(newInstance) ?
                    _.map(newInstance, function (instance) {
                        return instance.toJSON();
                    }) :
                    newInstance.toJSON();
                Model.publishCreate(publishData, !req.options.mirror && req);
            }
            // do your after create stuff here
            // Send JSONP-friendly response if it's supported
            res.ok({status: 200, message: 'ok', results: newInstance});
        });


    }
}