我試圖讓我的控制器操作儘可能輕量,所以我正在實現服務層。現在我已經驗證和消毒。我知道驗證應該在服務層完成,但是如何進行消毒?我想在出現驗證錯誤時重新渲染輸入數據。輸入驗證,消毒和服務層
//userService.js function
function register(data, callback) {
if (!data) {
return callback(new Error('Here some error...'));
}
/* Sanitize and validate the data */
/* Method #1 */
//If not valid then call back with validationErrors
if (notValid) {
return callback({
validationErrors: {
'username': 'Username is already in use.',
'email': 'Invalid characters.',
}
});
}
/* Method #2 */
if (notValid) {
return callback({
fields: {
//We put here a sanitized fields
},
validationErrors: {
'username': 'Username is already in use.',
'email': 'Invalid characters.',
}
});
}
};
//userController.js function
// GET/POST: /register
function registerAction(request, response, next) {
if (request.method === 'POST') {
var registerData = {
username: request.body['username'],
password: request.body['password'],
email: request.body['email'],
firstName: request.body['firstName'],
lastName: request.body['lastName'],
};
register(registerData, function(error, someDataIfSucceed) {
if (error) {
//Re-post the data so the user wont have to fill the form again
//Sanitize registerData variable here.
return response.render('register', {
error: error,
validationErrors: error.validationErrors
});
};
//User registered succesfully.
return response.render('registerSuccess');
});
return;
}
return response.render('register');
}
我看到那裏2個選項。
- 使用原始POST數據調用服務函數'register',清理並驗證它,然後僅推回驗證錯誤。如果存在驗證錯誤,則在渲染視圖之前在控制器中清理它們。
- 與第一個相同,但我們推回驗證錯誤和消毒字段。
這沒有一個正確的答案,哪一個最適合您的需求? – WiredPrairie