W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
think.controller.rest
繼承自 think.controller.base,用來(lái)處理 Rest 接口。
export default class extends think.controller.rest {
}
module.exports = think.controller("rest", {
})
標(biāo)識(shí)此 controller 對(duì)應(yīng)的是 Rest 接口。如果在 init
方法里將該屬性設(shè)置為false
,那么該 controller 不再是一個(gè) Rest 接口。
獲取 method 方式。默認(rèn)從 http method 中獲取,但有些客戶端不支持發(fā)送 delete, put 之類的請(qǐng)求,所以可以設(shè)置為從 GET 里的一個(gè)參數(shù)獲取。
export default class extends think.controller.rest {
init(http){
super.init(http);
//設(shè)置 _method,表示從 GET 參數(shù)獲取 _method 字段的值
//如果沒(méi)有取到,則從 http method 中獲取
this._method = "_method";
}
}
當(dāng)前 Rest 對(duì)應(yīng)的 Resource 名稱。
資源 ID
資源對(duì)應(yīng) model 的實(shí)例。
可以在魔術(shù)方法__before
中進(jìn)行字段過(guò)濾,分頁(yè),權(quán)限校驗(yàn)等功能。
export default class extends think.controller.rest{
__before(){
//過(guò)濾 password 字段
this.modelInstance.field("password", true);
}
}
獲取資源數(shù)據(jù),如果有 id,拉取一條,否則拉取列表。
//方法實(shí)現(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ù)
//方法實(shí)現(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ù)
//方法實(shí)現(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ù)
//方法實(shí)現(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});
}
}
找不到方法時(shí)調(diào)用
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
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: