Save Time & Money With This One Weird Trick! Dependency Injection in Express
Note: this is an old post, ported from my old blog. I originally wrote it for a talk I gave on June 27, 2023, so some of the details (library choices, code structure) are dated.
What is Dependency Injection?
Dependency Injection
Dependency injection is a solution to implement Inversion of Control, which is one of the SOLID principles (D: Dependency Inversion). Very roughly, the Dependency inversion principle states that functions or classes shouldn't be concerned with building / instantiating their dependencies. Instead, they should receive their dependencies as arguments and let other code deal with setting up the dependency.
Dependency injection is the group of techniques used to enable a class or function to specify which dependencies they need without needing to worry about the details on how to get or create each dependency.
Source: Dependency injection with Node.js, Express.js and TypeScript
Inversion of Control
In object-oriented design, the dependency inversion principle is a specific methodology for loosely coupled software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. The principle states:
- High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
- Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
Why should you care?
Cost efficiency of software maintenance
If you want to switch from:
Mailgun <> Sendgrid || Ajv <> Zod || Sequelize <> Prisma || Moment <> Luxon
you may have to do a significant rewrite in areas of your codebase that shouldn't care about the dependency you are changing. You will do more work than is necessary each time you swap one dependency for another.
A note about Dependency Injection & the Single-responsibility Principle (SRP)
Building dependencies within your business logic code violates the SRP. The SRP is intended to make your code easier to comprehend & more resilient to change. In general, code costs more to maintain (extend & fix) than it did to develop initially. This is because requirements evolve during initial development (via scope creep or prototype feedback) & after initial release (via new features, changes to existing features & bug fixes). SRP is a time saving (& therefore cost saving) technique.
Easier-to-write, quicker-to-run automated tests
If tests are easy to write, your dev team will write more tests.
The problem: Writing flexible code & performant automated tests is a difficult problem with a juicy reward. Business logic changes as requirements evolve. Business logic is the most likely part of your code to change over time. If your business logic is concerned with dependency implementation details, then you have a larger blast radius for each change you make & you likely have unnecessary amounts of code duplication to set up these dependencies. The problem is evident when trying to create a robust automated testing suite.
Unit tests are tests that act on a singular "unit" of your code. Each unit test will ideally test as little code as possible. This makes it easier to ensure your tests are easy to read, easy to write & easy to change when the code they test changes.
When working with 3rd party dependencies (e.g. your DB, the Twilio API, Plaid API, USPS API, PayPal API, etc), you have to mock these dependencies, otherwise you are testing them. This is bad for 3 reasons:
- Waste of CI minutes
($) - Waste of developer time - waiting for a 3rd party call to return every time you run a test
($$) - Sometimes it's just not easy to write test code to work with 3rd party dependencies because these dependencies are not built for this purpose
($$$)- E.g. mocking calls to Twilio to send SMS, but not actually paying for SMS
Without DI, each unit test in your system will be responsible for stubbing calls to the tested code's dependencies (e.g. sending Twilio SMS or charging PayPal are things you don't want to actually do in a test).
With DI, you can write mocks for your dependency types/classes & stubs for your dependency methods once & re-use them throughout your tests. This makes it easier for your team to test a full user signup flow (including sending an SMS message via Twilio & charging their PayPal account) without actually calling any external dependencies.
How can you use it?
Example: RIVET's ETL pipeline
Why is this a good candidate for Dependency Injection?
- Ever-growing feature set
- We want to reduce the impact of expensive & manual UAT every time new features & changes to old features are rolled out
- Arduous to test
- Many separate systems → can't easily isolate testing to one system manually without building tooling → so if
Dev Awants to testSystem C, butDev Bis working on fixing upstreamSystem B, thenDev Ahas difficulties in testingSystem CbecauseSystem Bhas to be working or simulated
- Many separate systems → can't easily isolate testing to one system manually without building tooling → so if
Exhibit A: Health check endpoints that test DB connections
This is the smallest useful example I could find in our codebase: a /ping endpoint that checks whether the API can reach the database. It started life inline in app.ts:
// server/src/app.ts
// health check endpoint
app.get('/ping', async (_req, res) => {
try {
await sequelize.query(`SELECT 1`, { type: QueryTypes.SELECT });
return res.status(200).json({ message: 'service running' });
} catch (error) {
return res.status(500).json({ message: 'service error' });
}
});
The handler reaches out & grabs the global sequelize instance itself. To test it, you either need a real database or you need to mock a module import.
1. Separate the ping endpoint from the main application constructor logic
1.a. Create healthController.ts & move the ping logic to it
// server/src/feature/api/controllers/healthController.ts
import { QueryTypes } from 'sequelize';
import { RivetApiResponse as Response, RivetRequest as Request, sequelize } from '../../../rivet-foundation';
export const ping = async (_req: Request, res: Response) => {
try {
// test DB connection
await sequelize.query(`SELECT 1`, { type: QueryTypes.SELECT });
return res.status(200).json({ message: 'service running' });
} catch (error) {
return res.status(500).json({ message: 'service error' });
}
};
export * as HealthController from './healthController';
1.b. Pass the HealthController.ping method into Express's .get()
// server/src/app.ts
// health check endpoint
app.get('/ping', HealthController.ping);
Nothing about the behavior has changed yet. The logic just has a home of its own, which makes the next step possible.
2. Rework .ping() to accept dependencies (this is the Dependency Injection part)
Instead of being a route handler, ping becomes a function that takes its dependencies as arguments & returns a route handler. The real sequelize instance is the default, so production code doesn't have to care:
// server/src/feature/api/controllers/healthController.ts
import { Sequelize } from 'sequelize-typescript';
import { QueryTypes } from 'sequelize';
import { NextFunction } from 'express';
import {
RivetApiResponse as Response,
RivetRequest as Request,
ExpressRouteFunc,
sequelize,
} from '../../../rivet-foundation';
export function ping(db: Sequelize = sequelize): ExpressRouteFunc {
return async function (_req: Request, res: Response, _next?: NextFunction) {
try {
// test DB connection
await db.query(`SELECT 1`, { type: QueryTypes.SELECT });
res.status(200);
return res.json({ message: 'service running' });
} catch (error) {
res.status(500);
return res.json({ message: 'service error' });
}
};
}
export * as HealthController from './healthController';
The route registration calls the function to get the handler:
// server/src/app.ts
// health check endpoint
app.get('/ping', HealthController.ping());
3. Write tests that inject a mocked ORM dependency
Now the test can hand ping a fake database. No real DB, no module mocking, no network:
// server/src/tests/api/healthController.unit.test.ts
import { RivetApiResponse as Response, RivetRequest as Request } from '../../rivet-foundation';
import { HealthController } from '../../feature/api/controllers/healthController';
import MockRequest from '../mocks/request.mock';
import MockResponse from '../mocks/response.mock';
import { NextFunction } from 'express';
import { Sequelize } from 'sequelize-typescript';
import { SequelizeMock } from '../mocks/sequelize.mock';
describe('HealthController', () => {
let mockRequest: MockRequest;
let mockResponse: MockResponse;
let nextFunction: NextFunction;
beforeEach(() => {
mockRequest = {};
mockResponse = {
json: jest.fn(),
status: jest.fn(),
};
nextFunction = jest.fn();
});
describe('/ping', () => {
test('Application can connect to the database', async () => {
const db: SequelizeMock = {
query: jest.fn().mockReturnValue(true),
};
const expectedResponse = { status: 200, json: { message: 'service running' } } as unknown as Response;
await HealthController.ping(db as unknown as Sequelize)(mockRequest as Request, mockResponse as Response);
expect(mockResponse.json).toBeCalledWith(expectedResponse.json);
expect(mockResponse.status).toBeCalledWith(expectedResponse.status);
expect(nextFunction).toBeCalledTimes(0);
});
test('Application cannot connect to the database', async () => {
const db: SequelizeMock = {
query: jest.fn().mockImplementation(() => {
throw new Error();
}),
};
const expectedResponse = { status: 500, json: { message: 'service error' } } as unknown as Response;
await HealthController.ping(db as unknown as Sequelize)(mockRequest as Request, mockResponse as Response);
expect(mockResponse.json).toBeCalledWith(expectedResponse.json);
expect(mockResponse.status).toBeCalledWith(expectedResponse.status);
expect(nextFunction).toBeCalledTimes(0);
});
});
});
Both the happy path & the "database is down" path are covered in a few milliseconds, & the "down" case is something you could never reliably reproduce against a real database in CI.
Exhibit B: More complicated API endpoints & the repository pattern
The health check is a toy. The same move works on real endpoints: we reworked an upsertWorkers endpoint on our public API to accept its dependencies (via a repository that wraps the ORM) instead of importing them, then added tests against a mocked repository. This was still a work in progress when I gave the talk, so I don't have a tidy before/after to show, but the steps are identical:
- Rework the handler to accept its dependencies
- Add tests that inject mocks
Additional Reading
- A practical guide to DI with great examples: Dependency injection with Node.js, Express.js and TypeScript
- Read everything Martin Fowler writes: Inversion of Control Containers and the Dependency Injection pattern