0
# Server Management
1
2
Classes for defining and managing OpenAPI server configurations with variable support and extension capabilities.
3
4
## Capabilities
5
6
### Server Class
7
8
Implementation class for OpenAPI server objects with fluent variable management.
9
10
```typescript { .api }
11
/**
12
* Server implementation class
13
*/
14
class Server implements ServerObject {
15
url: string;
16
description?: string;
17
variables: { [v: string]: ServerVariable };
18
[k: IExtensionName]: IExtensionType;
19
20
/**
21
* Create a new server instance
22
* @param url - Server URL with optional variables
23
* @param desc - Optional server description
24
*/
25
constructor(url: string, desc?: string);
26
27
/**
28
* Add a server variable
29
* @param name - Variable name (used in URL template)
30
* @param variable - ServerVariable instance
31
*/
32
addVariable(name: string, variable: ServerVariable): void;
33
}
34
```
35
36
**Usage Examples:**
37
38
```typescript
39
import { Server, ServerVariable } from "openapi3-ts";
40
41
// Basic server
42
const prodServer = new Server(
43
"https://api.example.com/v1",
44
"Production server"
45
);
46
47
// Server with variables
48
const apiServer = new Server(
49
"https://{environment}.example.com/{version}",
50
"Configurable API server"
51
);
52
53
// Add server variables
54
apiServer.addVariable("environment", new ServerVariable(
55
"prod",
56
["prod", "staging", "dev"],
57
"Server environment"
58
));
59
60
apiServer.addVariable("version", new ServerVariable(
61
"v1",
62
["v1", "v2"],
63
"API version"
64
));
65
66
// Use with OpenAPI builder
67
import { oas30 } from "openapi3-ts";
68
69
const spec = oas30.OpenApiBuilder.create()
70
.addServer(prodServer)
71
.addServer(apiServer)
72
.getSpec();
73
```
74
75
### ServerVariable Class
76
77
Implementation class for server variables with enum and default value support.
78
79
```typescript { .api }
80
/**
81
* Server variable implementation class
82
*/
83
class ServerVariable implements ServerVariableObject {
84
enum?: string[] | boolean[] | number[];
85
default: string | boolean | number;
86
description?: string;
87
[k: IExtensionName]: IExtensionType;
88
89
/**
90
* Create a new server variable
91
* @param defaultValue - Default value for the variable
92
* @param enums - Optional array of allowed values
93
* @param description - Optional variable description
94
*/
95
constructor(
96
defaultValue: string | boolean | number,
97
enums?: string[] | boolean[] | number[],
98
description?: string
99
);
100
}
101
```
102
103
**Usage Examples:**
104
105
```typescript
106
import { ServerVariable } from "openapi3-ts";
107
108
// String variable with enum
109
const environmentVar = new ServerVariable(
110
"production",
111
["production", "staging", "development"],
112
"Deployment environment"
113
);
114
115
// Numeric variable with range
116
const portVar = new ServerVariable(
117
8080,
118
[8080, 8443, 9000],
119
"Server port number"
120
);
121
122
// Boolean variable
123
const tlsVar = new ServerVariable(
124
true,
125
[true, false],
126
"Whether to use TLS"
127
);
128
129
// Variable without enum (any value allowed)
130
const tenantVar = new ServerVariable(
131
"default",
132
undefined,
133
"Tenant identifier"
134
);
135
```
136
137
## Server Interface Definitions
138
139
Core interfaces that the implementation classes satisfy.
140
141
```typescript { .api }
142
/**
143
* Server object interface
144
*/
145
interface ServerObject extends ISpecificationExtension {
146
url: string;
147
description?: string;
148
variables?: { [v: string]: ServerVariableObject };
149
}
150
151
/**
152
* Server variable object interface
153
*/
154
interface ServerVariableObject extends ISpecificationExtension {
155
enum?: string[] | boolean[] | number[];
156
default: string | boolean | number;
157
description?: string;
158
}
159
```
160
161
## Utility Functions
162
163
Helper functions for working with server configurations.
164
165
```typescript { .api }
166
/**
167
* Get an extension value from a server object
168
* @param obj - Object with potential extensions
169
* @param extensionName - Extension name (must start with 'x-')
170
* @returns Extension value or undefined
171
*/
172
function getExtension(
173
obj: ISpecificationExtension | undefined,
174
extensionName: string
175
): any;
176
177
/**
178
* Add an extension to a server object
179
* @param obj - Object to add extension to
180
* @param extensionName - Extension name (must start with 'x-')
181
* @param extension - Extension value
182
*/
183
function addExtension(
184
obj: ISpecificationExtension | undefined,
185
extensionName: string,
186
extension: any
187
): void;
188
```
189
190
## Complete Examples
191
192
### Multi-Environment Server Setup
193
194
```typescript
195
import { oas30, Server, ServerVariable } from "openapi3-ts";
196
197
// Create environment-specific servers
198
const servers = [
199
new Server("https://api.production.com", "Production server"),
200
new Server("https://api.staging.com", "Staging server"),
201
new Server("https://api.dev.com", "Development server")
202
];
203
204
// Create configurable server with variables
205
const configurableServer = new Server(
206
"https://{subdomain}.example.com/{basePath}",
207
"Configurable server endpoint"
208
);
209
210
configurableServer.addVariable("subdomain", new ServerVariable(
211
"api",
212
["api", "api-v2", "beta-api"],
213
"API subdomain"
214
));
215
216
configurableServer.addVariable("basePath", new ServerVariable(
217
"v1",
218
["v1", "v2", "beta"],
219
"API base path version"
220
));
221
222
// Build OpenAPI spec with servers
223
const spec = oas30.OpenApiBuilder.create()
224
.addTitle("Multi-Environment API")
225
.addVersion("1.0.0")
226
.addServer(servers[0]) // Production
227
.addServer(servers[1]) // Staging
228
.addServer(servers[2]) // Development
229
.addServer(configurableServer) // Configurable
230
.getSpec();
231
232
console.log(JSON.stringify(spec.servers, null, 2));
233
```
234
235
### Server with Custom Extensions
236
237
```typescript
238
import { Server, ServerVariable, addExtension } from "openapi3-ts";
239
240
// Create server with custom extensions
241
const server = new Server(
242
"https://api.example.com",
243
"Enhanced API server"
244
);
245
246
// Add custom extensions to server
247
addExtension(server, "x-rate-limit", {
248
requests: 1000,
249
window: "1h"
250
});
251
252
addExtension(server, "x-datacenter", "us-east-1");
253
254
// Create variable with extensions
255
const versionVar = new ServerVariable(
256
"v1",
257
["v1", "v2", "v3"],
258
"API version"
259
);
260
261
addExtension(versionVar, "x-deprecated-versions", ["v1"]);
262
addExtension(versionVar, "x-beta-versions", ["v3"]);
263
264
server.addVariable("version", versionVar);
265
266
// Verify extensions
267
console.log(server["x-rate-limit"]); // { requests: 1000, window: "1h" }
268
console.log(versionVar["x-deprecated-versions"]); // ["v1"]
269
```
270
271
### Complex Server Configuration
272
273
```typescript
274
import { oas31, Server, ServerVariable } from "openapi3-ts";
275
276
// Create a complex server setup for microservices
277
const createMicroserviceServer = (serviceName: string) => {
278
const server = new Server(
279
`https://{environment}-{serviceName}.api.company.com/{version}`,
280
`${serviceName} microservice endpoint`
281
);
282
283
server.addVariable("environment", new ServerVariable(
284
"prod",
285
["prod", "stage", "dev", "local"],
286
"Deployment environment"
287
));
288
289
server.addVariable("serviceName", new ServerVariable(
290
serviceName,
291
[serviceName], // Only this service name allowed
292
`Service name (fixed as ${serviceName})`
293
));
294
295
server.addVariable("version", new ServerVariable(
296
"v1",
297
["v1", "v2"],
298
"API version"
299
));
300
301
return server;
302
};
303
304
// Build OpenAPI 3.1 spec with microservice servers
305
const spec = oas31.OpenApiBuilder.create()
306
.addTitle("Microservices API Gateway")
307
.addVersion("1.0.0")
308
.addServer(createMicroserviceServer("users"))
309
.addServer(createMicroserviceServer("orders"))
310
.addServer(createMicroserviceServer("payments"))
311
.addServer(createMicroserviceServer("inventory"))
312
.getSpec();
313
314
// Each server will have properly configured variables
315
spec.servers?.forEach(server => {
316
console.log(`Server: ${server.url}`);
317
console.log(`Variables:`, Object.keys(server.variables || {}));
318
});
319
```
320
321
### Server Variable Validation
322
323
```typescript
324
import { ServerVariable } from "openapi3-ts";
325
326
// Helper function to create validated server variables
327
function createValidatedVariable(
328
defaultValue: string | number | boolean,
329
allowedValues?: (string | number | boolean)[],
330
description?: string
331
): ServerVariable {
332
// Validate default value is in allowed values if provided
333
if (allowedValues && !allowedValues.includes(defaultValue)) {
334
throw new Error(`Default value ${defaultValue} not in allowed values: ${allowedValues}`);
335
}
336
337
return new ServerVariable(defaultValue, allowedValues, description);
338
}
339
340
// Usage with validation
341
try {
342
const validVar = createValidatedVariable("prod", ["prod", "dev"], "Environment");
343
console.log("Valid variable created:", validVar);
344
345
const invalidVar = createValidatedVariable("invalid", ["prod", "dev"], "Environment");
346
} catch (error) {
347
console.error("Validation failed:", error.message);
348
// Output: "Validation failed: Default value invalid not in allowed values: prod,dev"
349
}
350
```
351
352
## Extension Utility Functions
353
354
Utility functions for working with specification extensions on server objects.
355
356
```typescript { .api }
357
/**
358
* Get extension value from an object that supports specification extensions
359
* @param obj - Object with potential extensions
360
* @param extensionName - Extension name (must start with 'x-')
361
* @returns Extension value or undefined if not found
362
*/
363
function getExtension(obj: ISpecificationExtension | undefined, extensionName: string): any;
364
365
/**
366
* Add extension to an object that supports specification extensions
367
* @param obj - Object to add extension to
368
* @param extensionName - Extension name (must start with 'x-')
369
* @param extension - Extension value
370
*/
371
function addExtension(
372
obj: ISpecificationExtension | undefined,
373
extensionName: string,
374
extension: any
375
): void;
376
```
377
378
### Extension Utility Usage
379
380
```typescript
381
import { Server, ServerVariable, getExtension, addExtension } from "openapi3-ts";
382
383
// Create server and add extensions
384
const server = new Server("https://api.example.com", "API Server");
385
386
// Add extensions using utility function
387
addExtension(server, "x-rate-limit", { requests: 1000, window: "1h" });
388
addExtension(server, "x-health-check", "/health");
389
addExtension(server, "x-load-balancer", "round-robin");
390
391
// Retrieve extensions using utility function
392
const rateLimit = getExtension(server, "x-rate-limit");
393
const healthCheck = getExtension(server, "x-health-check");
394
395
console.log("Rate limit config:", rateLimit);
396
// Output: "Rate limit config: { requests: 1000, window: '1h' }"
397
398
console.log("Health check endpoint:", healthCheck);
399
// Output: "Health check endpoint: /health"
400
401
// Check for non-existent extension
402
const missing = getExtension(server, "x-nonexistent");
403
console.log("Missing extension:", missing); // Output: "Missing extension: undefined"
404
```