藍圖動作 (請勿與隱含的 藍圖「動作」路由 混淆) 是設計用於處理模型的通用動作。 可以將它們視為應用程式的預設行為。 例如,如果您有一個 User.js
模型,則 find
、create
、update
、destroy
、populate
、add
和 remove
動作會隱含地存在,而無需您編寫它們。
預設情況下,藍圖 RESTful 路由 和 快捷路由 會繫結到其對應的藍圖動作。 然而,任何藍圖動作都可以透過在該控制器檔案中建立自訂動作 (例如 ParrotController.find
) 來覆寫特定控制器的藍圖動作。
目前版本的 Sails 隨附以下藍圖動作
如果您的應用程式啟用了 WebSockets,則大多數藍圖動作都具有即時功能。 例如,如果 find 藍圖動作收到來自 socket 用戶端的請求,它將訂閱該 socket 以接收未來的通知。 然後,每當使用藍圖動作 (例如 update) 變更記錄時,Sails 都會發布某些通知。
理解特定藍圖動作行為的最佳方法是閱讀其參考頁面 (或查看上面的清單)。 但是,如果您正在尋找 Sails 藍圖 API 中即時功能如何運作的概觀,請參閱概念 > 即時性。(如果您不介意某些細節過時,您甚至可能想查看2013 年原始的「Sails.js 簡介」影片。)
如需更深入了解 Sails 中藍圖動作發布的所有通知,請參閱
您也可以透過定義具有相同名稱的自訂動作來覆寫控制器的任何藍圖動作。
// api/controllers/user/UserController.js
module.exports = {
/**
* A custom action that overrides the built-in "findOne" blueprint action.
* As a dummy example of customization, imagine we were working on something in our app
* that demanded we tweak the format of the response data, and that we only populate two
* associations: "company" and "friends".
*/
findOne: function (req, res) {
sails.log.debug('Running custom `findOne` action. (Will look up user #'+req.param(\'id\')...');
User.findOne({ id: req.param('id') }).omit(['password'])
.populate('company', { select: ['profileImageUrl'] })
.populate('top8', { omit: ['password'] })
.exec(function(err, userRecord) {
if (err) {
switch (err.name) {
case 'UsageError': return res.badRequest(err);
default: return res.serverError(err);
}
}
if (!userRecord) { return res.notFound(); }
if (req.isSocket) {
User.subscribe(req, [user.id]);
}
return res.ok({
model: 'user',
luckyCoolNumber: Math.ceil(10*Math.random()),
record: userRecord
});
});
}
}
或者,我們可以將其建立為
api/controllers/user/findone.js
中的獨立動作,或使用 actions2。