Skip to content

instance limit

awekrx edited this page May 29, 2026 · 1 revision

instance-limit

Import

import { instanceLimit } from '@dev-suite/decorators/instance-limit'

Category

  • class

Use Case

Restrict number of class instances when resource duplication is unsafe.

Replaces

  • Manual static counters in constructors
  • Ad-hoc guard logic spread across classes

Example 1

Without decorator

class Scheduler {
  private static created = 0;

  constructor() {
    Scheduler.created += 1;
    if (Scheduler.created > 1) {
      throw new Error('Only one Scheduler instance is allowed');
    }
  }
}

With decorator

import { instanceLimit } from '@dev-suite/decorators/instance-limit';

@instanceLimit({ maxInstances: 1, message: 'Only one Scheduler instance is allowed' })
class Scheduler {
  constructor() {}
}

Why better

  • Removes repetitive static counter boilerplate
  • Limit policy is explicit and reusable

Example 2

Without decorator

class QueueWorker {
  private static created = 0;

  constructor() {
    QueueWorker.created += 1;
    if (QueueWorker.created > 4) throw new Error('worker pool overflow');
  }
}

With decorator

import { instanceLimit } from '@dev-suite/decorators/instance-limit';

@instanceLimit({ maxInstances: 4 })
class QueueWorker {
  constructor() {}
}

Why better

  • Supports bounded pools, not only singleton-style limits
  • Cleaner constructor with no resource-accounting noise

Clone this wiki locally