Skip to content

createMethodDecorator

awekrx edited this page May 29, 2026 · 1 revision

createMethodDecorator

Import

import { createMethodDecorator } from '@dev-suite/decorators/createMethodDecorator'

Category

  • core

Use Case

Build reusable method decorators with shared before/after/wrap hooks.

Replaces

  • Descriptor wrapping boilerplate in each decorator
  • Different hook semantics across decorators

Example 1

Without decorator

function timed() {
  return function (_target: object, key: string | symbol, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = async function (...args: unknown[]) {
      const start = Date.now();
      try {
        return await original.apply(this, args);
      } finally {
        console.log(String(key), Date.now() - start);
      }
    };
  };
}

With decorator

import { createMethodDecorator } from '@dev-suite/decorators/createMethodDecorator';

const timed = () =>
  createMethodDecorator({
    wrap: ({ invoke, args, propertyKey }) => {
      const start = Date.now();
      try {
        return invoke(args);
      } finally {
        console.log(String(propertyKey), Date.now() - start);
      }
    },
  });

Why better

  • Centralizes cross-cutting behavior.
  • Method/class/property code stays focused on domain logic.

Example 2

Without decorator

function callCounter() {
  let count = 0;
  return function (_target: object, key: string | symbol, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = function (...args: unknown[]) {
      count += 1;
      console.log(String(key), count);
      return original.apply(this, args);
    };
  };
}

With decorator

import { createMethodDecorator } from '@dev-suite/decorators/createMethodDecorator';

const callCounter = () => {
  let count = 0;
  return createMethodDecorator({
    before: ({ propertyKey }) => {
      count += 1;
      console.log(String(propertyKey), count);
    },
  });
};

Why better

  • Second scenario reuses same policy without duplication.
  • Behavior is more consistent and easier to audit.

Clone this wiki locally