NestJS裝飾器實現(xiàn)GET請求
裝飾器實現(xiàn)GET請求
定義一個裝飾器 Get,用于在 Controller 類中裝飾 getList 方法,以便從指定的 url 發(fā)起一個 GET 請求。然后根據(jù)請求的結(jié)果調(diào)用 getList 方法,并將響應(yīng)數(shù)據(jù)或錯誤信息傳遞給它。
Get裝飾器
其中Get接收一個 url 字符串作為參數(shù),返回一個裝飾器函數(shù),該函數(shù)接收 target(類的原型對象)、key(方法名)、和 descriptor(方法的描述符)。
使用 Axios 發(fā)起 GET 請求,如果請求成功,則調(diào)用 fnc(即 getList)并傳入響應(yīng)數(shù)據(jù)和一個狀態(tài)對象;如果請求失敗,則也調(diào)用 fnc,并傳入錯誤信息和狀態(tài)對象。
import axios from "axios";
const Get = (url: string) => {
return (target: Object, key: any, descriptor: PropertyDescriptor) => {
console.log(key,descriptor)
const fnc = descriptor.value;//將原方法 fnc 存儲在變量中。
axios.get(url).then(res => {
fnc(res, {
status: 200,
success: true
})
}).catch(e => {
fnc(e, {
status: 500,
success: false
})
})
}
}
Controller類
包含一個構(gòu)造函數(shù)和一個被裝飾的方法 getList。getList 方法在接收到數(shù)據(jù)后可以進行相應(yīng)的處理,例如輸出數(shù)據(jù)到控制臺。
class Controller {
constructor() { }
@Get("https://maqib.cn/_next/data/NLsSYPIRJyj1wLXgylj6N/blog.json")
getList(res: any, status: string) {
// console.log(res.data)
}
}
優(yōu)化上面代碼
import axios from "axios";
const Get = (url: string) => {
return (target: Object, key: string | symbol, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
try {
const res = await axios.get(url);
// 調(diào)用原始方法并傳遞結(jié)果和狀態(tài)
return originalMethod.apply(this, [res, { status: 200, success: true }, ...args]);
} catch (e) {
// 處理錯誤情況
return originalMethod.apply(this, [e, { status: 500, success: false }, ...args]);
}
};
};
}
class Controller {
constructor() {}
@Get("https://maqib.cn/_next/data/NLsSYPIRJyj1wLXgylj6N/blog.json")
async getList(res?:any, status?: { status: number; success: boolean }) {
if (status?.success) {
console.log(res.data); // 正常響應(yīng)
} else {
console.error('Error:', res); // 錯誤處理
}
}
}
// 測試控制器
const controller = new Controller();
controller.getList(); // 調(diào)用 getList 方法到此這篇關(guān)于NestJS裝飾器實現(xiàn)GET請求的文章就介紹到這了,更多相關(guān)NestJS GET請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
express+mockjs實現(xiàn)模擬后臺數(shù)據(jù)發(fā)送功能
這篇文章主要介紹了express+mockjs實現(xiàn)模擬后臺數(shù)據(jù)發(fā)送功能,需要的朋友可以參考下2018-01-01
基于element-ui組件手動實現(xiàn)單選和上傳功能
在用戶使用過程中提出一鍵導(dǎo)入的功能,需求如下:點擊導(dǎo)入按鈕顯示提示框,然后是單選框以及上傳按鈕。這篇文章主要介紹了基于element-ui組件手動實現(xiàn)單選和上傳功能,需要的朋友可以參考下2018-12-12

