0
# Server Configuration
1
2
Core server setup and configuration functionality for integrating Inversify container with Express application. The `InversifyExpressServer` class handles route registration, middleware resolution, and HTTP context management.
3
4
## Capabilities
5
6
### InversifyExpressServer Class
7
8
Main server wrapper class that integrates Inversify dependency injection container with Express.js application.
9
10
```typescript { .api }
11
/**
12
* Wrapper for the express server with Inversify container integration
13
*/
14
class InversifyExpressServer {
15
/**
16
* Creates a new InversifyExpressServer instance
17
* @param container - Container loaded with all controllers and their dependencies
18
* @param customRouter - Optional express.Router custom router
19
* @param routingConfig - Optional routing configuration
20
* @param customApp - Optional express.Application custom app
21
* @param authProvider - Optional authentication provider constructor
22
* @param forceControllers - Optional boolean setting to force controllers (defaults to true)
23
*/
24
constructor(
25
container: interfaces.Container,
26
customRouter?: Router | null,
27
routingConfig?: RoutingConfig | null,
28
customApp?: Application | null,
29
authProvider?: (new () => AuthProvider) | null,
30
forceControllers?: boolean
31
);
32
33
/**
34
* Sets the configuration function to be applied to the application.
35
* Note that the config function is not actually executed until a call to build().
36
* This method is chainable.
37
* @param fn - Function in which app-level middleware can be registered
38
*/
39
setConfig(fn: ConfigFunction): this;
40
41
/**
42
* Sets the error handler configuration function to be applied to the application.
43
* Note that the error config function is not actually executed until a call to build().
44
* This method is chainable.
45
* @param fn - Function in which app-level error handlers can be registered
46
*/
47
setErrorConfig(fn: ConfigFunction): this;
48
49
/**
50
* Applies all routes and configuration to the server, returning the express application.
51
*/
52
build(): Application;
53
}
54
```
55
56
### Configuration Types
57
58
```typescript { .api }
59
/**
60
* Configuration function type for app-level setup
61
*/
62
type ConfigFunction = (app: Application) => void;
63
64
/**
65
* Routing configuration interface
66
*/
67
interface RoutingConfig {
68
/** Root path for all routes (default: '/') */
69
rootPath: string;
70
}
71
```
72
73
**Usage Examples:**
74
75
```typescript
76
import { Container } from "inversify";
77
import { InversifyExpressServer } from "inversify-express-utils";
78
import express from "express";
79
80
const container = new Container();
81
82
// Basic server setup
83
const server = new InversifyExpressServer(container);
84
const app = server.build();
85
86
// Server with configuration
87
const server2 = new InversifyExpressServer(container);
88
server2.setConfig((app) => {
89
app.use(express.json());
90
app.use(express.urlencoded({ extended: true }));
91
app.use("/api/docs", express.static("docs"));
92
});
93
94
server2.setErrorConfig((app) => {
95
app.use((error, req, res, next) => {
96
console.error(error);
97
res.status(500).json({ message: "Internal server error" });
98
});
99
});
100
101
const app2 = server2.build();
102
103
// Server with custom router and routing config
104
const customRouter = express.Router();
105
const server3 = new InversifyExpressServer(
106
container,
107
customRouter,
108
{ rootPath: "/api/v1" }
109
);
110
111
// Server with authentication provider
112
class CustomAuthProvider implements AuthProvider {
113
async getUser(req, res, next) {
114
// Custom authentication logic
115
return {
116
details: { id: 1, name: "User" },
117
isAuthenticated: async () => true,
118
isInRole: async (role) => role === "user",
119
isResourceOwner: async (resourceId) => true
120
};
121
}
122
}
123
124
const server4 = new InversifyExpressServer(
125
container,
126
null,
127
null,
128
null,
129
CustomAuthProvider
130
);
131
```
132
133
### HTTP Context Management
134
135
The server automatically creates and manages HTTP context for each request, providing access to the container, request/response objects, and user information.
136
137
```typescript { .api }
138
/**
139
* HTTP context interface providing request-scoped access to container and user info
140
*/
141
interface HttpContext<T = unknown> {
142
/** Child container created for this specific request */
143
container: interfaces.Container;
144
/** Express request object */
145
request: Request;
146
/** Express response object */
147
response: Response;
148
/** Authenticated user principal */
149
user: Principal<T>;
150
}
151
```
152
153
### Constants
154
155
```typescript { .api }
156
/** Default root path for routing */
157
const DEFAULT_ROUTING_ROOT_PATH: string = '/';
158
159
/** Error message for duplicate controller names */
160
const DUPLICATED_CONTROLLER_NAME: (name: string) => string;
161
162
/** Error message when no controllers are found */
163
const NO_CONTROLLERS_FOUND: string = 'No controllers have been found! Please ensure that you have register at least one Controller.';
164
```