Here is a custom decorator for Nest.Js:
import { SetMetadata } from '@nestjs/common';
import { PermissionPolicy } from '../permission.policy';
type ClassThatExtends<TClass = any> = new (...args) => TClass;
// Check if user has provided permission to access this route
export const Acl = <
// this means expecting the class not an instance,
TPolicyClass extends ClassThatExtends<PermissionPolicy>,
TActions extends (keyof InstanceType<TPolicyClass>)[],
>(
policyClass: TPolicyClass,
actions: TActions,
) => {
const policyInstance = new policyClass();
const requiredPermissions = actions.reduce((acc, actionName) => {
return [...acc, ...policyInstance[actionName]];
// >> TS2536: Type 'keyof InstanceType ' cannot be used to index type 'PermissionPolicy'.
}, [] as string[]);
return SetMetadata('aclPermissions', requiredPermissions);
};
What issue is present here and how can it be resolved?
Currently, I am addressing the error by suppressing it using the following approach, although I feel that there might be a better solution.
return [...acc, ...policyInstance[actionName as keyof PermissionPolicy]];
Expected usage example:
@Acl(AuthPolicy, ['update']) // The property 'update' is part of AuthPpolicy