SoFunction
Updated on 2025-04-10

NestJS decorator implements GET request

Decorators implement GET requests

Define a decoratorGet, used inController classDecorationgetList method, in order to get from the specifiedurlStart oneGETask. Then call according to the request resultgetList methodand pass the response data or error message to it.

Get Decorator

inGetReceives a url string as an argument and returns a decorator function that receives target (the prototype object of the class), key (the method name), and descriptor (the descriptor of the method).

Use Axios to initiate a GET request. If the request is successful, fnc (i.e. getList) is called and the response data and a state object are passed in; if the request fails, fnc is also called and error information and state object are passed in.

import axios from "axios";
const Get = (url: string) => {
	return (target: Object, key: any, descriptor: PropertyDescriptor) => {
		(key,descriptor)
		const fnc = ;//Storing the original method fnc in a variable.		(url).then(res => {
			fnc(res, {
				status: 200,
				success: true
			})
		}).catch(e => {
			fnc(e, {
				status: 500,
				success: false
			})
		})
	}
}

Controller class

Contains a constructor and a decorative methodgetListgetList methodAfter receiving the data, corresponding processing can be performed, such as outputting the data to the console.

class Controller {
	constructor() { }
	@Get("/_next/data/NLsSYPIRJyj1wLXgylj6N/")
	getList(res: any, status: string) {
		// ()
	}
}

Optimize the above code

import axios from "axios";

const Get = (url: string) => {
	return (target: Object, key: string | symbol, descriptor: PropertyDescriptor) => {
		const originalMethod = ;

		 = async function (...args: any[]) {
			try {
				const res = await (url);
				// Call the original method and pass the result and state				return (this, [res, { status: 200, success: true }, ...args]);
			} catch (e) {
				// Handle errors				return (this, [e, { status: 500, success: false }, ...args]);
			}
		};
	};
}

class Controller {
	constructor() {}

	@Get("/_next/data/NLsSYPIRJyj1wLXgylj6N/")
	async getList(res?:any, status?: { status: number; success: boolean }) {
		if (status?.success) {
			(); // Normal response		} else {
			('Error:', res); // Error handling		}
	}
}

// Test the controllerconst controller = new Controller();
(); // Call getList method

This is the end of this article about the implementation of GET requests by NestJS decorator. For more information about NestJS GET requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!