總述
Actions是Sails項目中對用戶端響應請求的部分,它是model和view的中間層,負責梳理業務邏輯。
Actions是項目中的路由,當用戶端請求一個URL時,将經由它執行邏輯并響應。
定義在何處
Actions通常定義在api/controllers目錄下。
Actions示例
Actions檔案通常有兩種組織形式,actions2(推薦)和傳統的。
Actions2:
module.exports = {
friendlyName: 'Welcome user',
description: 'Look up the specified user and welcome them, or redirect to a signup page if no user was found.',
inputs: {
userId: {
description: 'The ID of the user to look up.',
// By declaring a numeric example, Sails will automatically respond with `res.badRequest`
// if the `userId` parameter is not a number.
type: 'number',
// By making the `userId` parameter required, Sails will automatically respond with
// `res.badRequest` if it's left out.
required: true
}
},
exits: {
success: {
responseType: 'view',
viewTemplatePath: 'pages/welcome'
},
notFound: {
description: 'No user with the specified ID was found in the database.',
responseType: 'notFound'
}
},
fn: async function ({userId}) {
// Look up the user whose ID was specified in the request.
// Note that we don't have to validate that `userId` is a number;
// the machine runner does this for us and returns `badRequest`
// if validation fails.
var user = await User.findOne({ id: userId });
// If no user was found, respond "notFound" (like calling `res.notFound()`)
if (!user) { throw 'notFound'; }
// Display a personalized welcome view.
return {
name: user.name
};
}
};
使用傳統的(req, res)方法來寫actions會減少代碼量,但使用actions2有如下好處:
- 代碼不必依賴于req和res,使其更容易抽象成helper
- 可以及早确定actions需要的請求參數名和類型,在action運作時可以自動驗證
- 不必仔細分析代碼就能知道action所有可能的輸出結果
傳統:
module.exports = async function welcomeUser (req, res) {
// Get the `userId` parameter from the request.
// This could have been set on the querystring, in
// the request body, or as part of the URL used to
// make the request.
var userId = req.param('userId');
// If no `userId` was specified, or it wasn't a number, return an error.
if (!_.isNumeric(userId)) {
return res.badRequest(new Error('No user ID specified!'));
}
// Look up the user whose ID was specified in the request.
var user = await User.findOne({ id: userId });
// If no user was found, redirect to signup.
if (!user) {
return res.redirect('/signup' );
}
// Display the welcome view, setting the view variable
// named "name" to the value of the user's name.
return res.view('welcome', {name: user.name});
}
Controllers
生成Sails最快的方式就是把actions組織到controllers檔案中。例如:
module.exports = {
login: function (req, res) { ... },
logout: function (req, res) { ... },
signup: function (req, res) { ... },
};
獨立actions
對于大型成熟的系統,獨立的actions可能是比controllers更好的方式。并非多個actions寫在一個檔案中,而是每個action都有一個獨立的檔案在api/controller目錄下。如:
api/
controllers/
user/
login.js
logout.js
signup.js
保持“瘦”
和多數MVC架構一樣,controller都是很瘦的一層。因為可重用的代碼通常會被移到helpers或者提取到modules中。這使得項目變複雜的過程中更容易維護。
有一個規則:當使用同樣代碼的地方達到3處,即可将其移入helper中。