Skip to content

Instantly share code, notes, and snippets.

@vahidvdn
Last active February 21, 2024 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vahidvdn/b04b04f3973e7644d22d6e341960bcb6 to your computer and use it in GitHub Desktop.
Save vahidvdn/b04b04f3973e7644d22d6e341960bcb6 to your computer and use it in GitHub Desktop.
Custom Public Decorator instead of nestjs
import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
export const Public0 = () => SetMetadata(IS_PUBLIC_KEY, true); // nestjs way
export const reflectObj = {};
// custome way
export function Public() {
return function (
target: any,
methodName: string,
descriptor: PropertyDescriptor,
) {
console.log('Public!', target, descriptor);
const className = target.constructor.name;
console.log(`Class name: ${className}`);
console.log(`Method name: ${methodName}`);
// defineMetadata can be used as well
reflectObj[className] = {};
reflectObj[className][methodName] = true;
};
}
@vahidvdn
Copy link
Author

How to access in the jwt guard:

const className = context.getClass().name;
const methodName = context.getHandler().name;
console.log(context.getClass().name, context.getHandler().name);

const isPublicObj = reflectObj[className][methodName];

// if you used defineMetadata
const isPublicReflect = Reflect.getMetadata(
  IS_PUBLIC_KEY,
  context.getClass(),
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment