NestJS裝飾器實(shí)現(xiàn)GET請(qǐng)求
裝飾器實(shí)現(xiàn)GET請(qǐng)求
定義一個(gè)裝飾器 Get,用于在 Controller 類中裝飾 getList 方法,以便從指定的 url 發(fā)起一個(gè) GET 請(qǐng)求。然后根據(jù)請(qǐng)求的結(jié)果調(diào)用 getList 方法,并將響應(yīng)數(shù)據(jù)或錯(cuò)誤信息傳遞給它。
Get裝飾器
其中Get接收一個(gè) url 字符串作為參數(shù),返回一個(gè)裝飾器函數(shù),該函數(shù)接收 target(類的原型對(duì)象)、key(方法名)、和 descriptor(方法的描述符)。
使用 Axios 發(fā)起 GET 請(qǐng)求,如果請(qǐng)求成功,則調(diào)用 fnc(即 getList)并傳入響應(yīng)數(shù)據(jù)和一個(gè)狀態(tài)對(duì)象;如果請(qǐng)求失敗,則也調(diào)用 fnc,并傳入錯(cuò)誤信息和狀態(tài)對(duì)象。
import axios from "axios";
const Get = (url: string) => {
return (target: Object, key: any, descriptor: PropertyDescriptor) => {
console.log(key,descriptor)
const fnc = descriptor.value;//將原方法 fnc 存儲(chǔ)在變量中。
axios.get(url).then(res => {
fnc(res, {
status: 200,
success: true
})
}).catch(e => {
fnc(e, {
status: 500,
success: false
})
})
}
}
Controller類
包含一個(gè)構(gòu)造函數(shù)和一個(gè)被裝飾的方法 getList。getList 方法在接收到數(shù)據(jù)后可以進(jìn)行相應(yīng)的處理,例如輸出數(shù)據(jù)到控制臺(tái)。
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) {
// 處理錯(cuò)誤情況
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); // 錯(cuò)誤處理
}
}
}
// 測(cè)試控制器
const controller = new Controller();
controller.getList(); // 調(diào)用 getList 方法到此這篇關(guān)于NestJS裝飾器實(shí)現(xiàn)GET請(qǐng)求的文章就介紹到這了,更多相關(guān)NestJS GET請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
express+mockjs實(shí)現(xiàn)模擬后臺(tái)數(shù)據(jù)發(fā)送功能
這篇文章主要介紹了express+mockjs實(shí)現(xiàn)模擬后臺(tái)數(shù)據(jù)發(fā)送功能,需要的朋友可以參考下2018-01-01
基于Javascript實(shí)現(xiàn)彈出頁面效果
彈出層效果是一個(gè)很實(shí)用的功能,很多網(wǎng)站都采用了這種方式實(shí)現(xiàn)登錄和注冊(cè),下面小編通過本文給大家分享具體實(shí)現(xiàn)代碼,對(duì)js彈出頁面效果相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2016-01-01
基于element-ui組件手動(dòng)實(shí)現(xiàn)單選和上傳功能
在用戶使用過程中提出一鍵導(dǎo)入的功能,需求如下:點(diǎn)擊導(dǎo)入按鈕顯示提示框,然后是單選框以及上傳按鈕。這篇文章主要介紹了基于element-ui組件手動(dòng)實(shí)現(xiàn)單選和上傳功能,需要的朋友可以參考下2018-12-12
JS實(shí)現(xiàn)超簡(jiǎn)單的鼠標(biāo)拖動(dòng)效果
這篇文章主要介紹了JS實(shí)現(xiàn)超簡(jiǎn)單的鼠標(biāo)拖動(dòng)效果,涉及JavaScript響應(yīng)鼠標(biāo)事件動(dòng)態(tài)操作頁面元素的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11

