【NestJS】装饰器如何实现GET请求

在这里插入图片描述

装饰器实现GET请求

定义一个装饰器 Get,用于在 Controller 类中装饰 getList 方法,以便从指定的 url 发起一个 GET 请求。然后根据请求的结果调用 getList 方法,并将响应数据或错误信息传递给它。

Get装饰器

其中Get接收一个 url 字符串作为参数,返回一个装饰器函数,该函数接收 target(类的原型对象)、key(方法名)、和 descriptor(方法的描述符)。

使用 Axios 发起 GET 请求,如果请求成功,则调用 fnc(即 getList)并传入响应数据和一个状态对象;如果请求失败,则也调用 fnc,并传入错误信息和状态对象。


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类

包含一个构造函数和一个被装饰的方法 getListgetList 方法在接收到数据后可以进行相应的处理,例如输出数据到控制台。

class Controller {
    
    
	constructor() {
    
     }
	@Get("https://maqib.cn/_next/data/NLsSYPIRJyj1wLXgylj6N/blog.json")
	getList(res: any, status: string) {
    
    
		// console.log(res.data)
	}
}

优化上面代码


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);
				// 调用原始方法并传递结果和状态
				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); // 正常响应
		} else {
    
    
			console.error('Error:', res); // 错误处理
		}
	}
}

// 测试控制器
const controller = new Controller();
controller.getList(); // 调用 getList 方法

猜你喜欢

转载自blog.csdn.net/qq_38951259/article/details/142917396