この機能はまだ実験段階です。
このメソッドはまだ開発中であり、インターフェースや動作は予告なく変更される可能性があります。
指定されたIDを持つアクションに適用される新しいアクションミドルウェア関数を登録します。
sails.registerActionMiddleware(actionMiddlewareFns, actionIdentities);
アクションミドルウェア関数は、基本的にポリシーであり、プログラムで宣言するものです(sails.config.policiesを通じて宣言するのではなく)。実際、ポリシーは内部的にはアクションミドルウェアを使って実装されています。registerActionMiddleware()メソッドは、主にアプリに新しいポリシーを追加する方法として、カスタムフックで役立ちます。
| 引数 | 型 | 詳細 | |
|---|---|---|---|
| 1 | actionMiddlewareFns | 登録する1つ以上のミドルウェア関数。アクションミドルウェア(ポリシーと同様)は、req、res、およびnext引数を受け入れる関数でなければなりません。 |
|
| 2 | actionIdentities | アクションミドルウェアを適用するアクションを示す式。ワイルドカードには最後に*を使用します。例えば、user/*は、IDがuser/で始まるすべてのアクションに適用されます。式で指定されたアクションにアクションミドルウェアを適用しないことを示すには、先頭に!を使用します。例えば、!user/fooや!user/*。複数のID式は、コンマで区切って指定できます。例えば、pets/count,user/*,!user/tickle |
actionIdentities引数は、スタンドアロンアクションであるかのようにIDが表現されることを期待します。コントローラーファイル(例えば、UserController.js)内のアクションにアクションミドルウェアを適用するには、ファイル名の小文字バージョンを、"Controller"なし(例えば、user)で参照するだけです。
カスタムフックで適用される可能性のあるアクションミドルウェアの例として、ページビューカウンターを想像してください(このコードはフックの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'
);