此功能仍处于实验阶段。
此方法仍在开发中,其接口和/或行为可能会随时更改。
注册一个新的 action 中间件函数,该函数将应用于具有指定标识的 action。
sails.registerActionMiddleware(actionMiddlewareFns, actionIdentities);
Action 中间件函数本质上是 策略,您可以以编程方式声明(而不是通过 sails.config.policies)。事实上,策略是在后台使用 action 中间件实现的。registerActionMiddleware()
方法主要在 自定义钩子 中有用,作为向应用程序添加新策略的一种方式。
参数 | 类型 | 详情 | |
---|---|---|---|
1 | actionMiddlewareFns | 一个或多个要注册的中间件函数。Action 中间件(像策略一样)必须是接受 req 、res 和 next 参数的函数。 |
|
2 | actionIdentities | 表示 action 中间件应应用到的 action 或 actions 的表达式。在末尾使用 * 表示通配符;例如,user/* 将应用于所有标识以 user/ 开头的 action。在开头使用 ! 表示 action 中间件不应应用于表达式指定的 actions,例如 !user/foo 或 !user/* 。多个标识表达式可以通过逗号分隔来指定,例如 pets/count,user/*,!user/tickle |
actionIdentities
参数期望将标识表示为 独立 action。要将 action 中间件应用于控制器文件中的 action(例如UserController.js
),只需引用文件名的 无 "Controller" 的 小写版本(例如user
)。
作为一个可能在自定义钩子中应用的 action 中间件的示例,想象一个页面浏览量计数器(此代码可能添加到钩子的 initialize
方法中)
// Declare a local var to hold the number of views for each URL.
var pageViews = {};
// Register middleware to record each page view.
sails.registerActionMiddleware(
// First argument is the middleware to run
function countPage (req, res, next) {
// Initialize the page counter to zero if this is the first time we've seen this URL.
pageViews[req.url] = pageViews[req.url] || 0;
// Increment the page counter.
pageViews[req.url]++;
// Add the current page count to the request, so that it can be used in other middleware / actions.
req.currentPageCount = pageViews[req.url];
// Continue to the next matching middleware / action
next();
},
// Second argument is the actions to apply the middleware to. In this case, we want the
// hook to apply to all actions EXCEPT the `show-page-views` action supplied by this hook.
'*, !page-view-hook/show-page-views'
);