强制执行延迟控制器逻辑

Enforce deferring controller logic

我们正在尝试应用 John Papa AngularJS Style Guide 中列出的指南。

我们开始遵循的规则之一是 Defer Controller Logic:

Defer logic in a controller by delegating to services and factories.

Why?: Logic may be reused by multiple controllers when placed within a service and exposed via a function.

Why?: Logic in a service can more easily be isolated in a unit test, while the calling logic in the controller can be easily mocked.

Why?: Removes dependencies and hides implementation details from the controller.

这是我们过去违反的做法,将数据检索逻辑放入控制器而不是将其隔离在服务中。

现在我想让规则尽可能严格。理想情况下,如果将其中一项配置的服务作为依赖项传递给控制器​​,我希望 angular 抛出错误。它是否可以在 angular 级别上解决,或者我应该尝试单独解决它 - 例如,使用自定义 ESlint 规则静态地解决?

将不胜感激任何见解或提示。


特别是以下控制器违反了规则,因为它直接使用了$http service

function OrderController($http, $q, config, userInfo) {
    var vm = this;
    vm.checkCredit = checkCredit;
    vm.isCreditOk;

    function checkCredit() {
        var settings = {};

        return $http.get(settings)
            .then(function(data) {
               vm.isCreditOk = vm.total <= maxRemainingAmount;
            })
            .catch(function(error) {

            });
    };
}

此外,如果我对代码质量过分concerned/crazy,请告诉我:)

我已经写了一种变通方法,但它非常棘手和肮脏,因此绝不能使用它:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
    </head>
    <body ng-app="plunker" ng-controller="MainCtrl">
        <div ng-repeat="violation in codestyleViolations">
            {{violation}}
        </div>
    </body>
    <script>
    var app = angular.module('plunker', []).config(function($controllerProvider) { 
        $controllerProvider.$get[0] = 'trickyInjector';
    }).factory('trickyInjector', ['$injector', '$rootScope', function($injector, $rootScope) {
        $rootScope.codestyleViolations = [];
        var originalFunc = $injector.invoke;
        $injector.invoke = function(fn, self, locals, serviceName) {
            if (locals && locals.$scope && fn.indexOf('$http') !== -1) {
                $rootScope.codestyleViolations.push('ALYARM! ' + serviceName + ' uses $http');
            }
            return originalFunc.apply(this, arguments);
        };
        return $injector;
    }]).controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

    }]);
    </script>
</html>

UPD(2015 年 6 月):eslint-plugin-angular has built-in ng_no_services 将延迟控制器逻辑强制执行到服务或工厂的规则。


旧答案。

这里是 ESLint custom rule 限制一个函数,其名称以 ControllerCtrl 结尾,可以传入任何已配置的参数:

module.exports = function (context) {

    "use strict";

    var restrictedParams = context.options[0] || [];

    var check = function (node) {
        var name = node.id && node.id.name;

        if (/(Controller|Ctrl)$/.test(name) && node.params) {
            var params = node.params.map(
                function (param) {
                    return param.name;
                }
            );

            restrictedParams.filter(function (n) {
                if (params.indexOf(n) != -1) {
                    context.report(node, "This controller function uses a restricted dependency {{param}}.", {
                        param: n
                    });
                }
            });

        }
    };

    return {
        "FunctionDeclaration": check,
        "FunctionExpression": check
    }
};

示例配置 (eslint.json):

{
  "env": {
    "browser": true,
    "node": true,
    "jasmine": true
  },
  "globals": {
    "angular": true,
    "browser": true,
    "element": true,
    "by": false,
    "inject": false
  },
  "plugins": [
    "angularjs"
  ],
  "rules": {
    "ctrl-logic": [2, ["$http"]]
  }
}

现在,假设我定义了以下控制器(违反规则):

angular
    .module("app")
    .controller("AppController", AppController);


AppController.$inject = ["$scope", "ConnectionService", "ConfigService", "StatusService", "$http"];

function AppController($scope, ConnectionService, ConfigService, StatusService, $http) {
    ...
}

如果我运行eslint检查会报错:

$ grunt lint
Running "eslint:target" (eslint) task

app/app-controller.js
  8:0  error  This controller function uses a restricted dependency $http  ctrl-logic

✖ 1 problem

我可以想象有一些方法可以通过这种特定规则不会发现违规的方式来定义依赖关系,但是,如果您遵循样式指南中建议的建议,它应该适合您(适合我).