kaop-ts
kaop-ts copied to clipboard
Simple Yet Powerful Library of ES2016 Decorators with Strongly typed method Interceptors like BeforeMethod, AfterMethod, OnException, etc
Lightweight, solid, framework agnostic and easy to use library written in TypeScript to deal with Cross Cutting Concerns and improve modularity in your code.
Short Description (or what is an Advice)
This library provides a straightforward manner to implement Advices in your app. Advices are pieces of code that can be plugged in several places within OOP paradigm like 'beforeMethod', 'afterInstance'.. etc. Advices are used to change, extend, modify the behavior of methods and constructors non-invasively.
For in deep information about this technique check the resources.
Demo
https://jsbin.com/bogecojuvi/edit?js,console
Get started
npm install kaop-ts --save
Use a join point to plug it to any method/class:
import { afterMethod } from 'kaop-ts'
const double = afterMethod(meta => meta.result *= 2)
class DummyExample {
@double
static calculateSomething (num, num2) {
return num * num2
}
}
DummyExample.calculateSomething(3, 3) // 18
DummyExample.calculateSomething(5, 5) // 50
Whats new on 3.0
- Advices no longer use
this
to access several utilities. - Metadata properties have been renamed. Here you can check the reference .
- JoinPoints support multiple advices:
// join point decorators expect a list of advices
@beforeMethod(advice1, advice2, advice3)
// even you can provide an advice array using spread operator
@beforeMethod(...adviceList)
someMethod() {
}
Docs
-
Docs
-
Define an Advice
- As an anonymous function
- As an alias
- Using TypeScript generics
- Metadata Object
- Join Points
- Comunication between Advices
-
Parametrized Advices
- By Closure ref
-
Call-stack
- Async Advices
-
Define an Advice
-
Troubleshooting
- Babel setup
- Typescript setup
- Decorated methods should be class members instead properties
- Warning about Async Advices
-
Community ideas/contributions
- @jcjolley ES7 Async/Await Support
- @kailashthakuri Apply advices to all methods within a class
- @alexjoverm onException Join Point
-
Some Examples
(older version, API may defer)
- Working example about AOP/SRP with Angular 2+
- ES6 class constructor override
- Catch decorator
- Log decorator implementation
- Http decorator using axios
- Preact scoped stylesheet decorator
Resources
- Article series - Idiomatic JavaScript Backend - part 1/3
- Repo - based on Article series on dev.to
- Repo - AngularBeers (bcn) Separation of Concerns in modern JavaScript
- Video/Talk - AngularBeers (bcn) Separation of Concerns in modern JavaScript
- Article about Angular2+, Decorators and SRP
- Aspect Oriented Programming in Javascript (ES5+\Typescript)
- How To Handle Exceptions With Aspect Programming And Blame Covfefe
- kaop ES5 version
- Slides about AOP
Credits
Made using TypeScript Library Starter