JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Decorator Factories

22 min read ยท
In this lesson7

"Standardization and reuse are the key to success in the park," emphasizes Simon Masrani, the new owner of Jurassic Park. "We need systems that can be easily adapted to different dinosaur species, different parts of the park, and different security levels, but all according to uniform standards."

In the world of TypeScript, just as in managing Jurassic Park, we often need to create similar but slightly different decorators for different use cases. Decorator factories allow us to create highly configurable decorators that we can tailor to specific needs while maintaining a consistent structure and logic.

Introduction to Decorator Factories

A decorator factory is simply a function that returns a decorator, accepting configuration parameters. This allows creating decorators "on demand" with different behavior variants, based on the same template.

Main advantages of decorator factories:

  1. Reuse - we can create many different decorators from a single factory
  2. Configurability - we adapt the decorator's behavior to specific needs
  3. Consistency - all decorators from one factory share the same structure and concept
  4. Easier maintenance - a change in the factory updates all decorators created from it
  5. Typing - we can define factory parameters with precise types

Basic Decorator Factory Structure

A decorator factory typically has the following structure:

// Class decorator factory
function classDecoratorFactory(options: FactoryOptions) {
  // Returns a class decorator
  return function<T extends new (...args: any[]) => any>(target: T) {
    // Decorator implementation using options
    //
    return target; // or modified class
  };
}

// Method decorator factory
function methodDecoratorFactory(options: FactoryOptions) {
  // Returns a method decorator
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    // Decorator implementation using options
    //
    return descriptor;
  };
}

// Property decorator factory
function propertyDecoratorFactory(options: FactoryOptions) {
  // Returns a property decorator
  return function(target: any, propertyKey: string) {
    // Decorator implementation using options
    //
  };
}

Decorator Factory Examples in Jurassic Park

Let's see how we can use decorator factories in the context of managing Jurassic Park.

Example 1: Logging Decorator Factory for Different Subsystems

// Park subsystem types
type ParkSubsystem = "Security" | "Enclosures" | "Laboratory" | "Transport" | "Power Supply";

// Logging levels
type LogLevel = "Debug" | "Info" | "Warning" | "Error" | "Critical";

// Options interface for the logging decorator factory
interface LoggingOptions {
  subsystem: ParkSubsystem;
  level: LogLevel;
  registerCallOrder?: boolean;
  executionTime?: boolean;
}

// Logging decorator factory
function SystemLogging(options: LoggingOptions) {
  const { subsystem, level, registerCallOrder = false, executionTime = false } = options;

  // Call counter for each method
  const callCounter: Record<string, number> = {};

  // We return a method decorator
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    // Save the original method
    const originalMethod = descriptor.value;

    // Define a new method
    descriptor.value = function(...args: any[]) {
      // Record call order if needed
      if (registerCallOrder) {
        if (!callCounter[propertyKey]) {
          callCounter[propertyKey] = 0;
        }
        callCounter[propertyKey]++;
        console.log(`[${subsystem}] [Call #${callCounter[propertyKey]}] ${propertyKey}`);
      }

      // Initial logging
      console.log(`[${level}] [${subsystem}] Calling ${propertyKey}(${JSON.stringify(args)})`);

      // Time measurement if needed
      const startTime = executionTime ? performance.now() : 0;

      try {
        // Call the original method
        const result = originalMethod.apply(this, args);

        // Log after successful execution
        console.log(`[${level}] [${subsystem}] Completed ${propertyKey} - Status: Success`);

        // Log execution time if needed
        if (executionTime) {
          const endTime = performance.now();
          console.log(`[${subsystem}] Execution time ${propertyKey}: ${(endTime - startTime).toFixed(2)}ms`);
        }

        return result;
      } catch (error) {
        // Log on error
        console.error(`[${level}] [${subsystem}] Error in ${propertyKey}: ${error.message}`);

        // Propagate the error
        throw error;
      }
    };

    return descriptor;
  };
}

// Class managing the enclosure system
class EnclosuresSystem {
  // We use the factory to create different logging decorators
  @SystemLogging({ subsystem: "Enclosures", level: "Info" })
  openEnclosure(enclosureId: string): boolean {
    console.log(`Opening enclosure ${enclosureId}`);
    return true;
  }

  @SystemLogging({ subsystem: "Enclosures", level: "Warning", executionTime: true })
  closeEnclosure(enclosureId: string): boolean {
    console.log(`Closing enclosure ${enclosureId}`);

    // Simulate longer execution
    for (let i = 0; i < 1000000; i++) {
      // CPU load
    }

    return true;
  }

  @SystemLogging({ subsystem: "Enclosures", level: "Critical", registerCallOrder: true, executionTime: true })
  securityMode(enclosureId: string, reason: string): boolean {
    console.log(`Activating safety mode for enclosure ${enclosureId}. Reason: ${reason}`);

    // Simulate complex operation
    for (let i = 0; i < 2000000; i++) {
      // CPU load
    }

    return true;
  }
}

// Class managing the security system
class SecuritySystem {
  @SystemLogging({ subsystem: "Security", level: "Info" })
  checkStatus(): { status: string, activeAlarms: number } {
    return { status: "Normal", activeAlarms: 0 };
  }

  @SystemLogging({ subsystem: "Security", level: "Warning", executionTime: true })
  activateAlarm(area: string, level: number): boolean {
    console.log(`Activating alarm in area ${area} at level ${level}`);
    return true;
  }

  @SystemLogging({ subsystem: "Security", level: "Critical", registerCallOrder: true })
  evacuation(area: string): boolean {
    console.log(`Evacuation protocol for area ${area}`);
    return true;
  }
}

// Using classes with decorators
const enclosuresSystem = new EnclosuresSystem();
const securitySystem = new SecuritySystem();

// Testing
enclosuresSystem.openEnclosure("A-001");
enclosuresSystem.closeEnclosure("A-001");
enclosuresSystem.securityMode("A-001", "Test protocol");
enclosuresSystem.securityMode("A-001", "Repeat test");  // Will show this is the second call

securitySystem.checkStatus();
securitySystem.activateAlarm("Sector B", 2);
securitySystem.evacuation("Sector B");

In this example, the SystemLogging decorator factory creates method logging decorators that can be adapted to different subsystems, logging levels, and additional options such as recording call order or measuring execution time.

Example 2: Data Validation Decorator Factory

// Options interface for the validation decorator factory
interface ValidationOptions<T> {
  validator: (value: T) => boolean;
  errorMessage: string;
  exception?: typeof Error;
  transform?: (value: T) => T;
}

// Method parameter validation decorator factory
function ValidateParameter<T>(options: ValidationOptions<T>) {
  const { validator, errorMessage, exception = Error, transform } = options;

  // We return a method parameter decorator
  return function(target: Object, propertyKey: string, parameterIndex: number) {
    // Metadata key
    const validationKey = `validation_${propertyKey}_param_${parameterIndex}`;

    // Save validation metadata
    const validations = Reflect.getOwnMetadata(validationKey, target) || [];

    // Add new validation
    validations.push({
      index: parameterIndex,
      validator,
      errorMessage,
      exception,
      transform
    });

    // Save updated metadata
    Reflect.defineMetadata(validationKey, validations, target);

    // Check if a method decorator already exists
    if (!Reflect.hasMetadata(`validation_${propertyKey}_decorated`, target)) {
      // Mark the method as already decorated
      Reflect.defineMetadata(`validation_${propertyKey}_decorated`, true, target);

      // Get the method descriptor
      const originalMethod = target[propertyKey];

      // Override the method
      target[propertyKey] = function(...args: any[]) {
        // Get all validations for this method
        const validations = Reflect.getOwnMetadata(validationKey, target) || [];

        // Apply validations
        for (const validation of validations) {
          const { index, validator, errorMessage, exception, transform } = validation;

          // If the value is provided, validate it
          if (index < args.length) {
            const value = args[index];

            // Check validation
            if (!validator(value)) {
              throw new exception(`Validation error for parameter ${index} in method ${propertyKey}: ${errorMessage}`);
            }

            // Apply transformation if provided
            if (transform) {
              args[index] = transform(value);
            }
          }
        }

        // Call the original method
        return originalMethod.apply(this, args);
      };
    }
  };
}

// Set of predefined validators
// Non-empty string validator
function NotEmpty() {
  return ValidateParameter<string>({
    validator: (str) => str !== null && str !== undefined && str.trim() !== '',
    errorMessage: "Value may not be empty"
  });
}

// Minimum length validator
function MinLength(length: number) {
  return ValidateParameter<string>({
    validator: (str) => str !== null && str !== undefined && str.length >= length,
    errorMessage: `Value must have at least ${length} characters`
  });
}

// Numeric range validator
function Range(min: number, max: number) {
  return ValidateParameter<number>({
    validator: (num) => num >= min && num <= max,
    errorMessage: `Value must be in range from ${min} to ${max}`,
    // Optionally we can clamp the value to the range
    transform: (num) => Math.min(Math.max(num, min), max)
  });
}

// Positive number validator
function Positive() {
  return ValidateParameter<number>({
    validator: (num) => num > 0,
    errorMessage: "Value must be positive"
  });
}

// Date format validator
function FormatDate(format: RegExp = /^\d{4}-\d{2}-\d{2}$/) {
  return ValidateParameter<string>({
    validator: (str) => format.test(str),
    errorMessage: "Value must be in date format YYYY-MM-DD"
  });
}

// Class for managing dinosaur data
class DinosaurManagement {
  // Create a new dinosaur
  addDinosaur(
    @NotEmpty() @MinLength(3) name: string,
    @NotEmpty() species: string,
    @Positive() @Range(0, 100) age: number,
    @Positive() weight: number,
    @FormatDate() additionDate: string
  ): string {
    const dinosaurId = `DINO-${Date.now()}`;

    console.log(`Added new dinosaur:`);
    console.log(`- ID: ${dinosaurId}`);
    console.log(`- Name: ${name}`);
    console.log(`- Species: ${species}`);
    console.log(`- Age: ${age} years`);
    console.log(`- Weight: ${weight} kg`);
    console.log(`- Date added: ${additionDate}`);

    return dinosaurId;
  }

  // Update dinosaur data
  updateDinosaur(
    @NotEmpty() dinosaurId: string,
    @Range(0, 100) age?: number,
    @Positive() weight?: number
  ): boolean {
    console.log(`Updating dinosaur ${dinosaurId}:`);

    if (age !== undefined) {
      console.log(`- New age: ${age} years`);
    }

    if (weight !== undefined) {
      console.log(`- New weight: ${weight} kg`);
    }

    return true;
  }

  // Transfer dinosaur to a new enclosure
  moveDinosaur(
    @NotEmpty() dinosaurId: string,
    @NotEmpty() toEnclosure: string,
    @FormatDate() transferDate: string
  ): boolean {
    console.log(`Transferring dinosaur ${dinosaurId} to enclosure ${toEnclosure} on ${transferDate}`);
    return true;
  }
}

// Testing the class with parameter validation
const dinoManagement = new DinosaurManagement();

try {
  // Correct call
  dinoManagement.addDinosaur(
    "Blue",
    "Velociraptor",
    5,
    150,
    "2023-09-15"
  );

  // Incorrect call - empty name
  dinoManagement.addDinosaur(
    "",  // Empty name
    "Tyrannosaurus",
    8,
    7500,
    "2023-09-15"
  );
} catch (error) {
  console.error(error.message);
}

try {
  // Correct call
  dinoManagement.updateDinosaur("DINO-123", 6, 160);

  // Incorrect call - negative weight
  dinoManagement.updateDinosaur("DINO-123", 6, -100);
} catch (error) {
  console.error(error.message);
}

try {
  // Correct call
  dinoManagement.moveDinosaur("DINO-123", "B-002", "2023-09-20");

  // Incorrect call - invalid date format
  dinoManagement.moveDinosaur("DINO-123", "B-003", "20/09/2023");
} catch (error) {
  console.error(error.message);
}

In this example, we created a parameter validation decorator factory that allows creating different validators such as NotEmpty, MinLength, Range, Positive, and FormatDate. Thanks to this, we can easily apply validation to method parameters in a declarative way.

Example 3: Permission Decorator Factory

// Park permission levels
enum PermissionLevel {
  Guest = 0,
  Employee = 1,
  Manager = 2,
  Administrator = 3
}

// System actions
type SystemAction = "read" | "record" | "deletion" | "administration";

// Mapping permission levels to allowed actions
const permissionsMap: Record<PermissionLevel, SystemAction[]> = {
  [PermissionLevel.Guest]: ["read"],
  [PermissionLevel.Employee]: ["read", "record"],
  [PermissionLevel.Manager]: ["read", "record", "deletion"],
  [PermissionLevel.Administrator]: ["read", "record", "deletion", "administration"]
};

// Security context interface
interface SecurityContext {
  user: string;
  permissionLevel: PermissionLevel;
  tokens?: string[];
}

// Permission denied error
class PermissionError extends Error {
  constructor(action: string, requiredLevel: PermissionLevel, currentLevel: PermissionLevel) {
    super(`No permission for action ${action}. Required level: ${PermissionLevel[requiredLevel]}, current: ${PermissionLevel[currentLevel]}`);
    this.name = "PermissionError";
  }
}

// Permission decorator factory
function RequiresPermission(requiredAction: SystemAction, errorMessage?: string) {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function(this: { securityContext?: SecurityContext }, ...args: any[]) {
      // Check if we have a security context
      if (!this.securityContext) {
        throw new Error("Missing security context");
      }

      const { permissionLevel } = this.securityContext;

      // Check if the user has the action for their permission level
      const allowedActions = permissionsMap[permissionLevel] || [];

      if (!allowedActions.includes(requiredAction)) {
        // Find the minimum permission level needed for this action
        let minimumLevel: PermissionLevel = PermissionLevel.Administrator;

        for (const [level, actions] of Object.entries(permissionsMap)) {
          if (actions.includes(requiredAction) && Number(level) < minimumLevel) {
            minimumLevel = Number(level) as PermissionLevel;
          }
        }

        throw new PermissionError(
          requiredAction,
          minimumLevel,
          permissionLevel
        );
      }

      // Call the original method
      return originalMethod.apply(this, args);
    };

    return descriptor;
  };
}

// Simplified versions for frequently used levels
function ForGuests() {
  return RequiresPermission("read");
}

function ForEmployees() {
  return RequiresPermission("record");
}

function ForManagers() {
  return RequiresPermission("deletion");
}

function ForAdministrators() {
  return RequiresPermission("administration");
}

// Park management system class
class ParkManagementSystemClass {
  securityContext?: SecurityContext;

  constructor() {
    // No security context by default
  }

  // Method for setting the security context
  login(user: string, permissionLevel: PermissionLevel): void {
    this.securityContext = { user, permissionLevel };
    console.log(`User ${user} logged in with permission level: ${PermissionLevel[permissionLevel]}`);
  }

  // Method accessible to everyone
  @ForGuests()
  getPublicInfo(): string {
    return "Public park information";
  }

  // Method accessible to employees and above
  @ForEmployees()
  updateDinosaurData(dinosaurId: string, data: any): boolean {
    console.log(`Updating dinosaur data ${dinosaurId}`);
    return true;
  }

  // Method accessible to managers and above
  @ForManagers()
  removeDinosaur(dinosaurId: string): boolean {
    console.log(`Deleting dinosaur ${dinosaurId}`);
    return true;
  }

  // Method accessible only to administrators
  @ForAdministrators()
  configurationChange(key: string, value: any): boolean {
    console.log(`Configuration change: ${key} = ${value}`);
    return true;
  }

  // Method using the factory directly
  @RequiresPermission("administration", "Only administrators can restart system")
  restartSystem(): boolean {
    console.log("Restarting system...");
    return true;
  }
}

// Testing the permission system
const system = new ParkManagementSystemClass();

// Test for guest
console.log("--- Test for guest ---");
system.login("JohnVisitor", PermissionLevel.Guest);

try {
  console.log(system.getPublicInfo());  // Should work
  system.updateDinosaurData("DINO-123", { age: 5 });  // Should throw error
} catch (error) {
  console.error(error.message);
}

// Test for employee
console.log("\n--- Test for employee ---");
system.login("JaneEmployee", PermissionLevel.Employee);

try {
  console.log(system.getPublicInfo());  // Should work
  system.updateDinosaurData("DINO-123", { age: 5 });  // Should work
  system.removeDinosaur("DINO-123");  // Should throw error
} catch (error) {
  console.error(error.message);
}

// Test for manager
console.log("\n--- Test for manager ---");
system.login("BobManager", PermissionLevel.Manager);

try {
  system.removeDinosaur("DINO-123");  // Should work
  system.configurationChange("maxDino", 100);  // Should throw error
} catch (error) {
  console.error(error.message);
}

// Test for administrator
console.log("\n--- Test for administrator ---");
system.login("AliceAdmin", PermissionLevel.Administrator);

try {
  system.configurationChange("maxDino", 100);  // Should work
  system.restartSystem();  // Should work
} catch (error) {
  console.error(error.message);
}

In this example, we created a permission decorator factory that enables controlling access to methods based on user permission levels. Based on it, we created simplified decorators for frequently used permission levels, such as ForGuests, ForEmployees, ForManagers, and ForAdministrators.

Example 4: Resource Management Decorator Factory

// Park resource types
type ResourceType = "dinosaur" | "enclosure" | "building" | "vehicle" | "equipment";

// Resource usage tracking interface
interface TrackedUsage {
  resourceId: string;
  type: ResourceType;
  startTime: Date;
  endTime?: Date;
  user: string;
  status: "inUse" | "completed" | "cancelled";
}

// Global resource usage registry
class ResourceUsageRegistry {
  private static instance: ResourceUsageRegistry;
  private history: TrackedUsage[] = [];
  private activeUsages: Map<string, TrackedUsage> = new Map();

  private constructor() {}

  // Method to get the singleton
  static getInstance(): ResourceUsageRegistry {
    if (!ResourceUsageRegistry.instance) {
      ResourceUsageRegistry.instance = new ResourceUsageRegistry();
    }
    return ResourceUsageRegistry.instance;
  }

  // Method to start tracking
  startTracking(resourceId: string, type: ResourceType, user: string): string {
    const usageId = `USE-${Date.now()}-${Math.floor(Math.random() * 1000)}`;

    const tracking: TrackedUsage = {
      resourceId,
      type,
      startTime: new Date(),
      user,
      status: "inUse"
    };

    this.activeUsages.set(usageId, tracking);

    console.log(`Started tracking resource ${type} ${resourceId} by ${user}`);

    return usageId;
  }

  // Method to stop tracking
  endTracking(usageId: string, success: boolean = true): boolean {
    if (!this.activeUsages.has(usageId)) {
      console.warn(`No active tracking found for ID: ${usageId}`);
      return false;
    }

    const tracking = this.activeUsages.get(usageId)!;
    tracking.endTime = new Date();
    tracking.status = success ? "completed" : "cancelled";

    this.history.push(tracking);
    this.activeUsages.delete(usageId);

    console.log(`Stopped tracking resource ${tracking.type} ${tracking.resourceId} by ${tracking.user} with status: ${tracking.status}`);

    return true;
  }

  // Method to check if a resource is currently in use
  isResourceInUse(resourceId: string, type: ResourceType): boolean {
    for (const [usageId, tracking] of this.activeUsages.entries()) {
      if (tracking.resourceId === resourceId && tracking.type === type) {
        return true;
      }
    }
    return false;
  }

  // Method to get resource usage history
  getResourceHistory(resourceId: string, type: ResourceType): TrackedUsage[] {
    return this.history.filter(tracking =>
      tracking.resourceId === resourceId && tracking.type === type
    );
  }

  // Method to get the number of active usages
  countActiveUses(): number {
    return this.activeUsages.size;
  }
}

// Options interface for the resource tracking decorator factory
interface ResourceTrackingOptions {
  resourceType: ResourceType;
  checkAccess?: boolean;
  resourceIdIndex?: number;
  unavailabilityMessage?: string;
}

// Resource tracking decorator factory
function TrackedResourceUsage(options: ResourceTrackingOptions) {
  const {
    resourceType,
    checkAccess = false,
    resourceIdIndex = 0,
    unavailabilityMessage = "Resource is currently unavailable"
  } = options;

  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function(...args: any[]) {
      // Get the resource ID from parameters
      const resourceId = args[resourceIdIndex];

      if (!resourceId) {
        throw new Error(`No resource ID provided (parameter #${resourceIdIndex})`);
      }

      // Get the registry
      const registry = ResourceUsageRegistry.getInstance();

      // If availability check is needed
      if (checkAccess && registry.isResourceInUse(resourceId, resourceType)) {
        throw new Error(`${unavailabilityMessage} (${resourceType} ${resourceId})`);
      }

      // Get the username from the object if available
      const user = this.user || "system";

      // Start tracking
      const usageId = registry.startTracking(resourceId, resourceType, user);

      try {
        // Call the original method
        const result = originalMethod.apply(this, args);

        // End tracking with success
        registry.endTracking(usageId, true);

        return result;
      } catch (error) {
        // End tracking with error
        registry.endTracking(usageId, false);

        // Propagate the error
        throw error;
      }
    };

    return descriptor;
  };
}

// Helper functions for frequently used resource types
function TrackedDinosaurUsage(options: Omit<ResourceTrackingOptions, "resourceType"> = {}) {
  return TrackedResourceUsage({ ...options, resourceType: "dinosaur" });
}

function TrackedEnclosureUsage(options: Omit<ResourceTrackingOptions, "resourceType"> = {}) {
  return TrackedResourceUsage({ ...options, resourceType: "enclosure" });
}

function TrackedVehicleUsage(options: Omit<ResourceTrackingOptions, "resourceType"> = {}) {
  return TrackedResourceUsage({
    ...options,
    resourceType: "vehicle",
    checkAccess: true,
    unavailabilityMessage: "Vehicle is currently in use"
  });
}

function TrackedEquipmentUsage(options: Omit<ResourceTrackingOptions, "resourceType"> = {}) {
  return TrackedResourceUsage({
    ...options,
    resourceType: "equipment",
    checkAccess: true,
    unavailabilityMessage: "Equipment is currently in use"
  });
}

// Park resource management class
class ParkResourcesManagement {
  user: string;

  constructor(user: string) {
    this.user = user;
  }

  // Tracking dinosaur examination
  @TrackedDinosaurUsage()
  conductResearchDinosaur(dinosaurId: string): { status: string, temperature: number } {
    console.log(`Performing examination of dinosaur ${dinosaurId}`);

    // Simulate long process
    for (let i = 0; i < 1000000; i++) {
      // CPU load
    }

    return { status: "healthy", temperature: 38.5 };
  }

  // Tracking dinosaur feeding
  @TrackedDinosaurUsage()
  feedDinosaur(dinosaurId: string, foodType: string, amount: number): boolean {
    console.log(`Feeding dinosaur ${dinosaurId} with ${foodType} (${amount} kg)`);

    // Simulate process
    for (let i = 0; i < 500000; i++) {
      // CPU load
    }

    return true;
  }

  // Tracking enclosure inspection
  @TrackedEnclosureUsage()
  inspectEnclosure(enclosureId: string): { status: string, problems: string[] } {
    console.log(`Inspecting enclosure ${enclosureId}`);

    // Simulate inspection
    for (let i = 0; i < 800000; i++) {
      // CPU load
    }

    return { status: "OK", problems: [] };
  }

  // Tracking vehicle usage
  @TrackedVehicleUsage()
  useVehicle(vehicleId: string, cel: string): boolean {
    console.log(`Using vehicle ${vehicleId} for destination: ${cel}`);

    // Simulate driving
    for (let i = 0; i < 1500000; i++) {
      // CPU load
    }

    return true;
  }

  // Tracking equipment usage
  @TrackedEquipmentUsage({ resourceIdIndex: 1 })
  useEquipment(cel: string, equipmentId: string): boolean {
    console.log(`Using equipment ${equipmentId} for purpose: ${cel}`);

    // Simulate usage
    for (let i = 0; i < 700000; i++) {
      // CPU load
    }

    return true;
  }

  // Direct factory usage with custom options
  @TrackedResourceUsage({
    resourceType: "building",
    checkAccess: true,
    resourceIdIndex: 0,
    unavailabilityMessage: "Building is currently under maintenance"
  })
  performBuildingMaintenance(buildingId: string, maintenanceType: string): boolean {
    console.log(`Maintenance of building ${buildingId}: ${maintenanceType}`);

    // Simulate maintenance
    for (let i = 0; i < 2000000; i++) {
      // CPU load
    }

    return true;
  }
}

// Testing the resource tracking system
async function testResourceTracking() {
  const employee1 = new ParkResourcesManagement("John");
  const employee2 = new ParkResourcesManagement("Alice");

  // Test dinosaur examination
  console.log("--- Test: Dinosaur examination ---");
  await employee1.conductResearchDinosaur("DINO-001");

  // Test dinosaur feeding
  console.log("\n--- Test: Dinosaur feeding ---");
  await employee2.feedDinosaur("DINO-001", "meat", 50);

  // Test enclosure inspection
  console.log("\n--- Test: Enclosure inspection ---");
  await employee1.inspectEnclosure("ZAG-001");

  // Test vehicle usage
  console.log("\n--- Test: Vehicle usage ---");

  try {
    // First employee uses the vehicle
    console.log("Employee 1 uses the vehicle...");
    const promise1 = employee1.useVehicle("JEEP-001", "Round park");

    // We try to use the same vehicle by another employee
    console.log("Attempt to use the same vehicle by Employee 2...");
    const promise2 = employee2.useVehicle("JEEP-001", "Transport");

    await Promise.all([promise1, promise2]);
  } catch (error) {
    console.error(`Error: ${error.message}`);
  }

  // Test equipment usage
  console.log("\n--- Test: Equipment usage ---");
  await employee1.useEquipment("Examination", "EQUIP-001");

  // Test building maintenance
  console.log("\n--- Test: Building maintenance ---");
  await employee2.performBuildingMaintenance("BLD-001", "Electrical");

  // Check number of active usages
  const registry = ResourceUsageRegistry.getInstance();
  console.log(`\nActive usages: ${registry.countActiveUses()}`);

  // Check resource history
  console.log("\nHistory for dinosaur DINO-001:");
  const dinoHistory = registry.getResourceHistory("DINO-001", "dinosaur");
  console.log(`Number of entries: ${dinoHistory.length}`);
  dinoHistory.forEach((entry, index) => {
    console.log(`[${index + 1}] ${entry.user}: ${new Date(entry.startTime).toLocaleTimeString()} - ${entry.endTime ? new Date(entry.endTime).toLocaleTimeString() : 'in progress'}`);
  });
}

// Run the test
testResourceTracking();

In this example, we created a decorator factory for tracking resource usage in Jurassic Park. The TrackedResourceUsage factory creates decorators that automatically register the start and end of resource usage, and can also check its availability. Based on it, we created simplified decorators for frequently used resource types, such as TrackedDinosaurUsage, TrackedEnclosureUsage, TrackedVehicleUsage, and TrackedEquipmentUsage.

Combining Decorator Factories

One of the greatest advantages of decorator factories is the ability to combine them, which allows creating more complex and flexible solutions.

// Combining decorator factories
function FullTracking(resourceType: ResourceType, logLevel: LogLevel = "Info") {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    // First apply logging
    SystemLogging({
      subsystem: resourceType === "dinosaur" ? "Dinosaurs" :
                 resourceType === "enclosure" ? "Enclosures" :
                 resourceType === "vehicle" ? "Transport" :
                 resourceType === "equipment" ? "Equipment" : "System",
      level: logLevel,
      executionTime: true
    })(target, propertyKey, descriptor);

    // Then apply resource tracking
    return TrackedResourceUsage({
      resourceType,
      checkAccess: resourceType === "vehicle" || resourceType === "equipment"
    })(target, propertyKey, descriptor);
  };
}

// Example of using combined factories
class ParkManagementV2 {
  user: string;
  securityContext?: SecurityContext;

  constructor(user: string, permissionLevel: PermissionLevel) {
    this.user = user;
    this.securityContext = { user, permissionLevel };
  }

  // Combining resource tracking, logging, and permissions
  @ForEmployees()
  @FullTracking("dinosaur", "Info")
  takeCareOfDinosaur(dinosaurId: string): boolean {
    console.log(`Taking care of dinosaur ${dinosaurId}`);
    return true;
  }

  // Combining resource tracking, logging, and permissions with a higher level
  @ForManagers()
  @FullTracking("enclosure", "Warning")
  modifyEnclosureSettings(enclosureId: string, settings: any): boolean {
    console.log(`Modifying enclosure settings ${enclosureId}`);
    return true;
  }

  // Combining all necessary decorators for a critical function
  @ForAdministrators()
  @FullTracking("equipment", "Critical")
  configureSecuritySystems(equipmentId: string, parameters: any): boolean {
    console.log(`Configuring security systems using ${equipmentId}`);
    return true;
  }
}

// Test combining decorator factories
function testFactoryChaining() {
  console.log("=== Test: Combining decorator factories ===");

  const employee = new ParkManagementV2("Mary", PermissionLevel.Employee);
  const manager = new ParkManagementV2("Bob", PermissionLevel.Manager);
  const admin = new ParkManagementV2("Alice", PermissionLevel.Administrator);

  // Test employee
  console.log("\n--- Test: Employee ---");
  try {
    employee.takeCareOfDinosaur("DINO-002");  // Should work
    employee.modifyEnclosureSettings("ZAG-002", { temperature: 30 });  // Should throw error
  } catch (error) {
    console.error(error.message);
  }

  // Test manager
  console.log("\n--- Test: Manager ---");
  try {
    manager.modifyEnclosureSettings("ZAG-002", { temperature: 30 });  // Should work
    manager.configureSecuritySystems("SEC-001", { level: "high" });  // Should throw error
  } catch (error) {
    console.error(error.message);
  }

  // Test administrator
  console.log("\n--- Test: Administrator ---");
  try {
    admin.configureSecuritySystems("SEC-001", { level: "high" });  // Should work
  } catch (error) {
    console.error(error.message);
  }
}

// Run the test
testFactoryChaining();

In this example, we show how different decorator factories can be combined to create comprehensive solutions. The FullTracking function combines logging and resource tracking decorators, and is then used together with permission decorators.

Best Practices for Creating Decorator Factories

1. Maintain Structural Consistency

Make sure all decorator factories have a similar structure and naming convention. This way, the code will be more readable and predictable.

// Consistent decorator factory structure
function DataLogging(options: LoggingOptions) { /* ... */ }
function DataValidation(options: ValidationOptions) { /* ... */ }
function DataTracking(options: TrackingOptions) { /* ... */ }

2. Use Appropriate Types for Parameters

Always specify precise types for factory parameters to ensure type safety and IDE support.

// Good typing
interface ValidationOptions<T> {
  validator: (value: T) => boolean;
  message: string;
}

function Validate<T>(options: ValidationOptions<T>) {
  //
}

3. Provide Sensible Default Values

Decorator factories should have reasonable default values for non-critical options.

function LogOperation(options: Partial<LoggingOptions> = {}) {
  const {
    level = "Info",
    detailed = false,
    executionTime = false
  } = options;

  //
}

4. Create Simplified Versions for Common Use Cases

For frequently used configurations, create specialized factories that make using decorators easier.

// Specialized versions for different logging levels
function LogDebug(detailed: boolean = false) {
  return LogOperation({ level: "Debug", detailed });
}

function LogInfo() {
  return LogOperation({ level: "Info" });
}

function LogWarning() {
  return LogOperation({ level: "Warning", executionTime: true });
}

function LogError() {
  return LogOperation({ level: "Error", detailed: true, executionTime: true });
}

5. Document Your Factories

Well-documented decorator factories make them easier to use.

/**
 * Creates a decorator that validates a method parameter.
 *
 * @param options - Validation options
 * @param options.validator - Function that checks value correctness
 * @param options.message - Error message for invalid values
 * @param options.transform - Optional function to transform the value
 *
 * @returns A method parameter decorator
 *
 * @example
 * class Example {
 *   method(@Validate({ validator: (x) => x > 0, message: "Must be positive" }) count: number) {
 *     //
 *   }
 * }
 */
function Validate<T>(options: ValidationOptions<T>) {
  //
}

6. Avoid Hidden Dependencies

Decorator factories should be explicit about their dependencies.

// Bad - hidden dependency
function LogToFile(filePath: string) {
  // Directly uses the file system
  const fs = require('fs');
  //
}

// Good - explicit dependency
function LogToFile(logger: FileLogger) {
  // Logger is passed as a parameter
  //
}

7. Test Your Decorator Factories

Write unit tests for your decorator factories to make sure they work as expected.

describe('ValidateRange', () => {
  it('should pass a value within range', () => {
    //
  });

  it('should throw an error for a value out of range', () => {
    //
  });

  it('should clamp the value to range when transformation is enabled', () => {
    //
  });
});

Use Cases for Decorator Factories

Decorator factories are particularly useful in the following cases:

  1. Frameworks and libraries - creating configurable decorators for framework users
  2. Cross-cutting concerns - logging, validation, security that must be adapted to many cases
  3. Environment configuration - adapting decorator behavior to different environments (development, production)
  4. Resource management - monitoring, tracking, and controlling access to resources
  5. Metrics collection - configuring how metrics are collected based on different parameters
  6. Access control - creating permission decorators for different levels and roles

Summary

Decorator factories in TypeScript are a powerful tool that allows creating flexible, configurable, and reusable decorators. Just as systems in Jurassic Park must be adapted to different needs and requirements while maintaining uniform safety standards, decorator factories enable creating consistent yet case-specific decorators.

Thanks to decorator factories, we can:

  1. Improve code reuse - by creating configurable decorator templates
  2. Increase readability - by hiding complex logic behind a simple, declarative interface
  3. Ensure consistency - by applying the same patterns and structures throughout the application
  4. Increase flexibility - by adapting decorators to different use cases

Decorator factories are an advanced TypeScript technique that requires a good understanding of decorators, but they offer enormous benefits in terms of code organization, reuse, and readability. When well designed, they become incredibly valuable tools in your programming arsenal.

Code for this lesson: index.ts
// Decorator factories - Configurable Jurassic Park systems
// A decorator factory = a function that returns a decorator with parameters

// === FACTORY: Role-based access control ===
function RequireRole(requiredRole: string) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function (...args: any[]) {
      const userRole = (this as any).currentUserRole || "guest";
      if (userRole !== requiredRole && userRole !== "admin") {
        console.error("[ACCESS DENIED] " + propertyKey + " requires the role: " + requiredRole);
        return null;
      }
      console.log("[AUTHORIZATION] " + userRole + " -> " + propertyKey + " OK");
      return originalMethod.apply(this, args);
    };

    return descriptor;
  };
}

// === FACTORY: Execution time limit ===
function Timeout(maxMs: number) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function (...args: any[]) {
      const start = Date.now();
      const result = originalMethod.apply(this, args);
      const elapsed = Date.now() - start;

      if (elapsed > maxMs) {
        console.warn("[TIMEOUT] " + propertyKey + " took " + elapsed + "ms (limit: " + maxMs + "ms)");
      }
      return result;
    };

    return descriptor;
  };
}

// === FACTORY: Retrying operations ===
function Retry(attempts: number, delayLabel: string = "retry") {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function (...args: any[]) {
      let lastError: Error | null = null;

      for (let i = 1; i <= attempts; i++) {
        try {
          const result = originalMethod.apply(this, args);
          if (i > 1) console.log("[" + delayLabel.toUpperCase() + "] Success after " + i + " attempts");
          return result;
        } catch (error: any) {
          lastError = error;
          console.warn("[" + delayLabel.toUpperCase() + "] Attempt " + i + "/" + attempts + " failed: " + error.message);
        }
      }

      throw lastError;
    };

    return descriptor;
  };
}

// === FACTORY: Validating parameters ===
function ValidateParams(validators: Record<number, (val: any) => boolean>) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function (...args: any[]) {
      for (const [indexStr, validator] of Object.entries(validators)) {
        const index = Number(indexStr);
        if (!validator(args[index])) {
          throw new Error("Validation of parameter #" + index + " failed in " + propertyKey);
        }
      }
      return originalMethod.apply(this, args);
    };

    return descriptor;
  };
}

// === A CLASS WITH DECORATOR FACTORIES ===
class ParkSecuritySystem {
  currentUserRole: string = "admin";
  private failCount: number = 0;

  @RequireRole("admin")
  @Timeout(100)
  initiateLockdown(sector: string): string {
    return "LOCKDOWN activated in sector " + sector;
  }

  @RequireRole("scientist")
  checkDNA(sampleId: string): string {
    return "DNA analysis of sample " + sampleId + " completed";
  }

  @Retry(3, "sensor")
  readSensor(sensorId: string): number {
    this.failCount++;
    if (this.failCount % 3 !== 0) {
      throw new Error("Sensor " + sensorId + " is not responding");
    }
    return Math.floor(Math.random() * 100);
  }

  @ValidateParams({ 0: (v: any) => typeof v === "string" && v.length >= 3 })
  registerDinosaur(name: string): string {
    return "Registered dinosaur: " + name;
  }
}

// === TESTING ===
const security = new ParkSecuritySystem();

console.log("=== Decorator factories ===\n");

// Test RequireRole
console.log(security.initiateLockdown("A1"));
security.currentUserRole = "guest";
security.checkDNA("DNA-001");
security.currentUserRole = "admin";

// Test Retry
console.log("\n=== Sensor reading (with retries) ===");
try {
  const reading = security.readSensor("S-042");
  console.log("Reading:", reading);
} catch (e: any) {
  console.error("Final error:", e.message);
}

// Test ValidateParams
console.log("\n=== Validation ===");
console.log(security.registerDinosaur("Rex"));
try {
  security.registerDinosaur("AB"); // name too short
} catch (e: any) {
  console.error("Error:", e.message);
}

// TODO: Create a factory @Cache(ttlMs) with an expiry time
// TODO: Create a factory @RateLimit(maxCalls, windowMs)

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is a decorator factory in TypeScript?

  2. 2. What happens when you declare two interfaces with the same name in TypeScript?

Hands-on tasks in the game

  • Code editor

    Create a Cache decorator (memoizing results), Retry decorator (retrying attempts), and Deprecated decorator (logging a warning) according to the instructions.

  • Click in order

    Click in the correct order: when a class has multiple decorators (@A @B @C class X), in what order do the stages proceed?

  • Horizontal ordering

    Arrange the tsconfig.json configuration that enables the legacy decorators mode with metadata (needed e.g. by NestJS):

  1. QuestionDecorator Factories
  2. Coding taskAdvanced Decorator Patterns
  3. Click in orderDecorator Evaluation Order
  4. Put in orderDecorator Configuration in tsconfig
  5. QuestionDeclaration Merging

Useful articles