Instead of using DataAnnotation in C# to add meta attributes on properties, I am seeking a similar functionality in TypeScript for a ldap model class. The goal is to have decorators that can set the LDAP attribute used in the LDAP directory internally.
export class LdapUser {
@ldapAttribute('sn')
sureName: string;
}
export function ldapAttribute(attributeName: string): (target: any, propertyKey: string) => void {
return function (target: any, propertyKey: string) {
Reflect.defineMetadata("ldapAttribute", attributeName, target, propertyKey);
}
}
Currently, fetching the value of the ldapAttribute
decorator requires passing object and attribute names as raw strings, like so:
let user = new LdapUser();
let sureNameAttribute = Reflect.getMetadata("ldapAttribute", user, "sureName");
This approach works but may lead to runtime errors if the attribute is renamed without updating the Reflect.getMetadata()
call. It also lacks intellisense support. Therefore, I am exploring a solution like this:
let sureNameAttribute = Reflect.getMetadata("ldapAttribute", user.sureName);
The challenge here is to find a way to reflectively extract the attribute name (sureName
) and class object (user
). While I have achieved this in C# using reflection, I need guidance on how to implement it in TS.
Workaround
Although not as seamless as using Reflection in C#, I came up with a workaround that is an improvement over plain strings:
export function getLdapAttribute<T>(instance: T, attributeName: keyof T) : string {
let value : string = Reflect.getMetadata("ldapAttribute", instance, attributeName);
return value;
}
Here is how you would use it:
let attributeValue = getLdapAttribute(user, "sureName");
While lacking intellisense, this workaround provides compiler error detection if the attribute name is incorrect or missing.