我正在使用一个特定的npm模块获取feed,我想做的是用相同的代码创建多个操作,尽管我不想重复整个代码。这是我的控制器:

module.exports = {

    buzzy: function (req, res) {
        var FeedParser = require('feedparser'),
            request = require('request');

        var req = request('http://rss.nytimes.com/services/xml/rss/nyt/Technology.xml'),
            feedparser = new FeedParser();

        req.on('error', function (error) {
            // handle any request errors
        });
        req.on('response', function (res) {
            var stream = this;

            if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));

            stream.pipe(feedparser);
        });


        feedparser.on('error', function (error) {
            // always handle errors
        });
        feedparser.on('readable', function () {
            // This is where the action is!
            var stream = this,
                meta = this.meta // **NOTE** the "meta" is always available in the context of the feedparser instance
                ,
                item;

            while (item = stream.read()) {
                var newData = item;
                   Buzzfeed.create({'title': newData.title, 'url': newData.link, 'source': 'nytimesTech', 'category': 'tech'}, function (err, newTitles) {
                        });

            }
        });

    }
};

所以类似于“buzzy”控制器操作,我想创建多个操作-下面是每个控制器中唯一的行
var req = request('http://rss.nytimes.com/services/xml/rss/nyt/Technology.xml'),


Buzzfeed.create({'title': newData.title, 'url': newData.link, 'source': 'nytimesTech', 'category': 'tech'}, function (err, newTitles) {
                            });

好奇的是,什么是实现这一点的最佳方法,这样我就不再重复了?

最佳答案

你可以使用服务。如果代码中有多个位置正在使用的函数,则可以使用它们。
请参阅此处的文档:Services

关于node.js - Sails.js-如何在多个 Controller 操作之间重用(大部分)此代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27496146/

10-11 09:33
查看更多