Background
Currently we have customize decorator requirement related with #85.
As framework provider we can't control how users using decorator with our framework. In fact, developers can freely define their decorator function anywhere with native support by TypeScript.
But, there is a problem while users directly using the native decorators, that the native decorators function is more like for the project itself, and it could be inconvenient for reusing in other project. The key problem is that the decorators is not compatible with the midway & egg's plugin mechanism.
when you want to encapsulate a decorator function to a plugin for others to reuse. it seems like, we should define it like this:
// plugin/app.ts
module.exports = (app) => {
app.enumerableDecorator = function () {
// ...
}
}
it seems like the decorators function could be mix up with other plugin object. And the after the definition, we could find it's difficult to use it:
// project/app.ts
module.exports = (app) => {
class Sth {
@app.enumerableDecorator(false)
foo() { ... }
}
}
In this case, to be more graceful to use decorator functions, we'd like to import it from the framework's uniform export.
Aims
There is inconvenience, so there is requirement. We want to change this situation, by:
- Provide uniform decorator register function, so that users wouldn't define it anywhere, and avoid the conflict between user-defined and framework-defined decorators.
- Make decorators compatible with plugin mechanism, so that users can encapsulate their decorator in plugin which can be simply install by NPM.
- Supply the consistent usage for developers to retrieve and use decorators.
Solution
For all the aims, we need a decorator manager
to achieve.
The manager is defined in the package/context
, and initialized in midway-core
, while we should refactor the old implements like midway-hsf
or midway-schedule
, to keep the on-premise core decorators clear and simple.
And the decorator manager is preset up on the app object, so that users can register decorators by app.decorator.register
in plugins. This could effect some logic in the web-loader.
// register
module.exports = (app) => {
app.registerDecorator('myCount', () => {
// ...
})
}
Last, we supply a definition in midway
which refer the singleton manager object, so that users can retrieve an use the decorators like:
import { DecoratorManager } from 'midway'
const { myCount } = DecoratorManager;
class UserController {
@myCount()
@get('/')
index() {
//...
}
}