Just like we have @annotations in Java Universe (Spring), we have @decorators in NodeJS (TypeScript) universe. These 2 enable us to carve out redundant code like caching, logging, validity of parameters etc.
From TypeScriptLang
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression , where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
- Abstract out redundant code
- Keep business logic clean
- Improve developer productivity
Look at this basic example
const getUsernameById(String userId){
const userName = CACHE.get("bucket", userId);
if(!_.isNil(userName)) {
return userName;
}
const user = UserModel.getById(userId);
CACHE.set("bucket", userId, user.name);
Log.info(
method: "getUsernameById"
key_1: "userId",
key_1_value: userId,
key_2: "userName",
key_2_value: userName
)
return user.name;
}
This can be reduced to following using decorators
@Cache
@Log
const getUsernameById(String userId){
const user = UserModel.getById(userId);
return user.name;
}
- node >= v14.18.2
- npm >= 6.14.15
git clone https://github.com/thekosmix/node-decorators
cd node-decorators
npm i
npx ts-node test.ts- @Cache: Caches the result of a method. The cache key is generated by concatenating the method's arguments.
- @Log: Logs information about a method's execution, with options to log request and response data.
- @Length: Validates the length of a class property.
- @Async: Executes a method asynchronously.
- @Rest: Exposes a method as a REST API endpoint.