Files
xen-orchestra/@vates/decorate-with/README.md
Julien Fontanet b9ff3db9b0 feat(decorate-with): decorateClass() (#6136)
Generalization of `decorateMethodsWith` which also works for accessors.

The suffix `With` is not part of the name because it's not fluent (unlike for `@decorateWith(decorator)`).

`decorateMethodsWith` is now a deprecated alias for this new implementation.
2022-03-10 11:51:57 +01:00

2.8 KiB

@vates/decorate-with

Package Version License PackagePhobia Node compatibility

Creates a decorator from a function wrapper

Install

Installation of the npm package:

> npm install --save @vates/decorate-with

Usage

decorateWith(fn, ...args)

Creates a new (legacy) method decorator from a function decorator, for instance, allows using Lodash's functions as decorators:

import { decorateWith } from '@vates/decorate-with'

class Foo {
  @decorateWith(lodash.debounce, 150)
  bar() {
    // body
  }
}

decorateClass(class, map)

Decorates a number of accessors and methods directly, without using the decorator syntax:

import { decorateClass } from '@vates/decorate-with'

class Foo {
  get bar() {
    // body
  }

  set bar(value) {
    // body
  }

  baz() {
    // body
  }
}

decorateClass(Foo, {
  // getter and/or setter
  bar: {
    // without arguments
    get: lodash.memoize,

    // with arguments
    set: [lodash.debounce, 150],
  },

  // method (with or without arguments)
  baz: lodash.curry,
})

The decorated class is returned, so you can export it directly.

To apply multiple transforms to an accessor/method, you can either call decorateClass multiple times or use @vates/compose:

decorateClass(Foo, {
  baz: compose([
    [lodash.debounce, 150]
    lodash.curry,
  ])
})

perInstance(fn, ...args)

Helper to decorate the method by instance instead of for the whole class.

This is often necessary for caching or deduplicating calls.

import { perInstance } from '@vates/decorateWith'

class Foo {
  @decorateWith(perInstance, lodash.memoize)
  bar() {
    // body
  }
}

Because it's a normal function, it can also be used with decorateClass, with compose or even by itself.

decorateMethodsWith(class, map)

Deprecated alias for decorateClass(class, map).

Contributions

Contributions are very welcomed, either on the documentation or on the code.

You may:

  • report any issue you've encountered;
  • fork and create a pull request.

License

ISC © Vates SAS