作用
抽象通用的参数处理操作,减少重复劳动概念
原始参数
用户输入的参数(与最终参数相比,它没有经过处理,所以称为原始的)最终参数
通过这个类处理过的,可以直接使用的参数API
所有方法都是连贯操作
from(String where, String name, String Type)
where
:指定从哪里获取原始参数,可以选择:
- cookie
- scookie
- session
- path
- get
- post
controller.prepare()
之间的顺序决定它们在path中的位置
name
:原始参数的名字Type
:原始参数的类型当 where = session、scookie 时,Type 不起作用,这个方法相当于:
return runtime.input[where][name];
其他时候,这个方法相当于: return runtime.input[where]['require' + Type](name);
by(Function cb)
处理原始参数的函数cb函数的声明为:
function (orignalInputValue){
// "this" is runtime
}
可以返回:
ApiError
:中断处理,直接展示错误thenable
:resolve的结果作为最终参数,如果reject则展示错误其他类型
:返回值作为最终参数
els(Function fn)
如果出错将被调用可以返回一个值,作为“默认值”,用该值继续程序,而不是停止并提示“数据不存在”
* 注意这个“默认值”不能是
thenable
或 ApiError
等,它们都被认为是最终参数或者显示一个自定义页面代替默认的“数据不存在”(此时不应该return任何东西)
但不可以既不显示页面又不返回数据,这样会挂起请求。
也不可以在这个函数中使用异步操作(会导致不可控的问题)。
process(Function fn)
最终参数产生后,可以通过fn函数再次过滤它的参数是之前通过by获得的最终参数(对els产生的无效)
返回值作为最终参数
sync()
标记这个准备函数是同步执行的注意:同步执行意味着它和其他准备函数是同步的,其内部仍然可以是异步
示例:
controller.prepare("lastRefresh").sync().from("get", "date", "Time").els(function(){
return new Date;
});
controller.prepare("user").sync().from("get", "userId", "ObjectId").by(CLS.User.getById);
controller.prepare("newFeeds").by(function(){
var q = new AV.Query(CLS.Feed);
q.equalTo("user", CLS.User.empty(this.user));
q.greaterThan("createdAt", this.lastRefresh);
return q.find();
});
上面例子中,lastRefresh
和 user
依次获取,试图获取 user
前,
lastRefresh
一定已经准备就绪。之后可以再加更多异步准备函数,这些异步准备函数将同时执行,它们都一定可以用
user
和
lastRefresh
,但它们之间不能互相访问对方的数据。
例:
handler.prepare("userName")
.from("get", "userId", "objectId")
.by(CLS.User.getById)
.process(function(user){
return user.get("username");
}).els(function(){
this.redirect('/login?location=' + this.input.header.url);
});
handler.main = function(rt){
// rt.userName = the user's username field
};