Last active
October 20, 2021 11:44
-
-
Save siandreev/c1f485874644d050df54cd60bd093d31 to your computer and use it in GitHub Desktop.
ControllerDecorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'reflect-metadata'; | |
const ControllerNameMetadataKey = Symbol('ControllerMetadata'); | |
const ControllerMetaUrl = Symbol('ControllerMetaUrl'); | |
function Controller(name: string) { | |
return function(target: Function) { | |
Reflect.defineMetadata(ControllerNameMetadataKey, name, target.prototype); | |
}; | |
} | |
function Action( | |
target: Object, | |
propertyKey: string, | |
descriptor: TypedPropertyDescriptor<any> | |
): TypedPropertyDescriptor<any> { | |
const originalMethod = descriptor.value; | |
descriptor.value = function methodWrapper(...args) { | |
const controllerName = Reflect.getMetadata(ControllerNameMetadataKey, target); | |
methodWrapper[ControllerMetaUrl] = "/" + controllerName + "/" + propertyKey; | |
originalMethod.apply(this, args); | |
}; | |
return descriptor; | |
} | |
@Controller("Account") | |
class AccountController { | |
@Action | |
public login(data: any): any { | |
const url = this.login[ControllerMetaUrl]; | |
console.log('Send request to', url, '\n data:', data); | |
} | |
} | |
const account = new AccountController(); | |
account.login({ username: "user", password: "111"}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment