think.controller.rest
繼承自 think.controller.base,用來處理 Rest 接口。
export default class extends think.controller.rest {
}
module.exports = think.controller("rest", {
})
標識此 controller 對應的是 Rest 接口。如果在 init
方法里將該屬性設置為false
,那么該 controller 不再是一個 Rest 接口。
獲取 method 方式。默認從 http method 中獲取,但有些客戶端不支持發(fā)送 delete, put 之類的請求,所以可以設置為從 GET 里的一個參數(shù)獲取。
export default class extends think.controller.rest {
init(http){
super.init(http);
//設置 _method,表示從 GET 參數(shù)獲取 _method 字段的值
//如果沒有取到,則從 http method 中獲取
this._method = "_method";
}
}
當前 Rest 對應的 Resource 名稱。
資源 ID
資源對應 model 的實例。
可以在魔術方法__before
中進行字段過濾,分頁,權限校驗等功能。
export default class extends think.controller.rest{
__before(){
//過濾 password 字段
this.modelInstance.field("password", true);
}
}
獲取資源數(shù)據(jù),如果有 id,拉取一條,否則拉取列表。
//方法實現(xiàn),可以根據(jù)需要修改
export default class extends think.controller.rest {
* getAction(){
let data;
if (this.id) {
let pk = yield this.modelInstance.getPk();
data = yield this.modelInstance.where({[pk]: this.id}).find();
return this.success(data);
}
data = yield this.modelInstance.select();
return this.success(data);
}
}
添加數(shù)據(jù)
//方法實現(xiàn),可以根據(jù)需要修改
export default class extends think.controller.rest {
* postAction(){
let pk = yield this.modelInstance.getPk();
let data = this.post();
delete data[pk];
if(think.isEmpty(data)){
return this.fail("data is empty");
}
let insertId = yield this.modelInstance.add(data);
return this.success({id: insertId});
}
}
刪除數(shù)據(jù)
//方法實現(xiàn),可以根據(jù)需要修改
export default class extends think.controller.rest {
* deleteAction(){
if (!this.id) {
return this.fail("params error");
}
let pk = yield this.modelInstance.getPk();
let rows = yield this.modelInstance.where({[pk]: this.id}).delete();
return this.success({affectedRows: rows});
}
}
更新數(shù)據(jù)
//方法實現(xiàn),可以根據(jù)需要修改
export default class extends think.controller.rest {
* putAction(){
if (!this.id) {
return this.fail("params error");
}
let pk = yield this.modelInstance.getPk();
let data = this.post();
delete data[pk];
if (think.isEmpty(data)) {
return this.fail("data is empty");
}
let rows = yield this.modelInstance.where({[pk]: this.id}).update(data);
return this.success({affectedRows: rows});
}
}
找不到方法時調用
export default class extends think.controller.rest {
__call(){
return this.fail(think.locale("ACTION_INVALID", this.http.action, this.http.url));
}
}
文檔地址:https://github.com/75team/www.thinkjs.org/tree/master/view/zh-CN/doc/2.0/api_controller_rest.md
更多建議: