@forivall/decorator
v1.2.0
Published
Simple function decorator/wrapping util, in typescript
Downloads
4
Readme
@forivall/decorator
Simple function decorator/wrapping util, in typescript
Installation
npm install --save @forivall/decorator
Usage
Using the following wrapper function for our examples
function log<F extends (...args: any[]): any>(fn: F, label: string): F {
return (...args: Parameters<F>) => {
console.log(`enter ${label}`)
const out: ReturnType<F> = fn(...args)
console.log(`exit ${label}`)
return out
} as F
}
wrap()
import {wrap} from '@forivall/decorator'
const doStuff = wrap(log, () => console.log('stuff'), 'doStuff')
doStuff()
// Output:
// enter doStuff
// stuff
// exit doStuff
decorator()
Create a decorator function
import decorator from '@forivall/decorator'
const logDecorator = decorator(log)
class Stuff {
@logDecorator('doStuff')
doIt() {
console.log('stuff')
}
}
new Stuff().doIt()
// Output:
// enter doStuff
// stuff
// exit doStuff
proxied()
Add metadata to a function that proxies another. Useful for the proxy pattern.
class Stuff {
doIt() {
console.log('stuff')
}
somethingElse() {
console.log('more stuff')
}
}
import {proxied} from '@forivall/decorator'
class StuffWrapper {
stuff = new Stuff()
}
interface StuffWrapper implements Stuff {}
Object.keys(Stuff.prototype).forEach((k) => {
StuffWrapper.prototype[k] = proxied(Stuff, k, function(this: StuffWrapper, ...args: unknown[]) {
return this.stuff[k](...args)
})
})
Credits
License
ISC