npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

global-object-factory

v1.0.0

Published

Global Object Factory for TypeScript - Lightweight dependency injection for legacy code

Readme

Global Object Factory for TypeScript

Lightweight dependency injection for legacy code. Replace 'new' with testable factories without major refactoring.

Introduction

ObjectFactory helps you make legacy code testable by replacing direct instantiation (new) with controllable factory functions. This enables dependency injection without requiring major architectural changes.

Quick Example

Replace direct instantiation with create() to make dependencies controllable:

// Before: Hard dependency
const emailService = new EmailService(connectionString);

// After: Testable dependency
import { create } from 'global-object-factory';
const emailService = create(EmailService)(connectionString);

Now you can inject test doubles in your tests without changing production code:

import { setOne } from 'global-object-factory';

setOne(EmailService, mockEmailService);
// Next create(EmailService)() call returns mockEmailService

Installation

Add to your project:

npm install global-object-factory

Or with yarn:

yarn add global-object-factory

Core Components

Global Object Factory: Making Dependencies Testable

Use Case: Your legacy code creates dependencies with new, making it impossible to inject test doubles.

Solution: Replace new with create() to enable dependency injection without major refactoring.

Breaking Dependencies

Transform hard dependencies into testable code:

// Legacy code with hard dependency
class UserService {
  processUser(id: number) {
    const repo = new SqlRepository("server=prod;...");
    const user = repo.getUser(id);
    // ...
  }
}

// Testable code using Global Object Factory
import { create } from 'global-object-factory';

class UserService {
  processUser(id: number) {
    const repo = create(SqlRepository)("server=prod;...");
    const user = repo.getUser(id);
    // ...
  }
}

In Tests

import { setOne, clearAll } from 'global-object-factory';

describe('UserService', () => {
  afterEach(() => {
    clearAll();
  });

  it('should process user successfully', () => {
    // Setup
    const mockRepo = new MockSqlRepository();
    mockRepo.users.set(123, { name: 'John', email: '[email protected]' });

    setOne(SqlRepository, mockRepo);

    // Act
    const service = new UserService();
    const result = service.processUser(123);

    // Assert
    expect(result).toEqual({ name: 'John', email: '[email protected]' });
  });
});

Test Double Injection

Use setOne for single-use mocks or setAlways for persistent test doubles:

import { ObjectFactory, setOne, setAlways } from 'global-object-factory';

// Single-use test double (consumed after first use)
setOne(EmailService, mockEmailService);

// Persistent test double (used for all calls)
setAlways(DatabaseService, mockDatabaseService);

// setOne takes priority over setAlways
setAlways(MyService, alwaysService);
setOne(MyService, onceService);
const service1 = create(MyService)(); // Returns onceService
const service2 = create(MyService)(); // Returns alwaysService

Factory Instance Usage

For more control, use ObjectFactory instances:

import { ObjectFactory } from 'global-object-factory';

describe('MyService', () => {
  let factory: ObjectFactory;

  beforeEach(() => {
    factory = new ObjectFactory();
  });

  afterEach(() => {
    factory.clearAll();
  });

  it('should use mock repository', () => {
    // Setup
    const mockRepo = new MockRepository();
    factory.setOne(Repository, mockRepo);

    // Act - your code calls create(Repository)() and gets mockRepo
    const service = new MyService(factory);
    const result = service.processData();

    // Assert
    expect(result).toEqual(expected);
  });
});

Global Singleton Pattern

Use the global singleton for convenience:

import { create, setOne, setAlways, clearAll } from 'global-object-factory';

// All functions use the global singleton
setAlways(EmailService, mockEmailService);

// Anywhere in your code
const service = create(EmailService)();

// Clean up in test teardown
afterEach(() => {
  clearAll();
});

Constructor Parameter Tracking

Implement IConstructorCalledWith to receive parameter information:

import { IConstructorCalledWith, ConstructorParameterInfo } from 'global-object-factory';

class TrackedService implements IConstructorCalledWith {
  constructor(
    public config: string,
    public port: number
  ) {}

  constructorCalledWith(params: ConstructorParameterInfo[]): void {
    // params[0] = { index: 0, type: 'string', value: 'localhost' }
    // params[1] = { index: 1, type: 'number', value: 8080 }
  }
}

const service = create(TrackedService)('localhost', 8080);
// constructorCalledWith is automatically called with parameter details

Object Registration

Register objects with IDs for clean test specifications:

const factory = new ObjectFactory();

// Complex configuration object
const dbConfig = {
  host: 'localhost',
  port: 5432,
  database: 'testdb'
};

// Register with ID
factory.register(dbConfig, 'testDbConfig');

// Later retrieve by ID
const config = factory.getRegistered<DatabaseConfig>('testDbConfig');

// Auto-generate IDs if not provided
const obj1 = { value: 1 };
const id = factory.register(obj1); // Returns 'auto_1'

Migration Examples

Before (Direct Instantiation)

class OrderProcessor {
  processOrder(orderId: string) {
    const db = new DatabaseConnection("prod-server");
    const emailService = new EmailService("smtp.example.com", 587);
    const order = db.getOrder(orderId);

    if (order.status === 'pending') {
      emailService.sendConfirmation(order.customerEmail);
    }
  }
}

After (Using Global Object Factory)

import { create } from 'global-object-factory';

class OrderProcessor {
  processOrder(orderId: string) {
    const db = create(DatabaseConnection)("prod-server");
    const emailService = create(EmailService)("smtp.example.com", 587);
    const order = db.getOrder(orderId);

    if (order.status === 'pending') {
      emailService.sendConfirmation(order.customerEmail);
    }
  }
}

In Tests

import { setOne, clearAll } from 'global-object-factory';

describe('OrderProcessor', () => {
  afterEach(() => clearAll());

  it('should send confirmation email for pending orders', () => {
    // Arrange
    const mockDb = new MockDatabase();
    mockDb.setOrder('123', { status: 'pending', customerEmail: '[email protected]' });

    const mockEmail = new MockEmailService();

    setOne(DatabaseConnection, mockDb);
    setOne(EmailService, mockEmail);

    // Act
    const processor = new OrderProcessor();
    processor.processOrder('123');

    // Assert
    expect(mockEmail.sentEmails).toContainEqual({
      to: '[email protected]',
      type: 'confirmation'
    });
  });
});

Requirements

  • Node.js 14+
  • TypeScript 4.5+
  • Any test framework (Jest, Mocha, Vitest, etc.)

License

See LICENSE.md