generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.ts
81 lines (71 loc) · 2.5 KB
/
registry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import cors from 'cors';
import express, { Express, NextFunction, Request, Response } from 'express';
import http from 'http';
import { DRPM_REGISTRY_URL } from '../config.js';
import { Logger } from '../utils/logger.js';
import handlers from './handlers.js';
export class Registry {
private app: Express;
private server?: http.Server;
private port: number | string;
constructor(port: number | string = process.env.PORT || 2092) {
this.app = express();
this.port = this.normalizePort(port) as string;
this.app.set('port', this.port);
// Load configurations and middleware here
this.loadConfigs();
this.setupRoutes();
}
// Initialize configurations and middleware
private loadConfigs(): void {
this.app.use(cors());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(express.raw({ type: 'application/octet-stream', limit: '10gb' }));
this.app.use((req: Request, _: Response, next: NextFunction) => {
req.url = decodeURIComponent(req.url);
Logger.log(`${req.method} ${req.url}`);
next();
});
}
// Define routes or import from external routes file
private setupRoutes(): void {
// Assuming registry has specific routes
this.app.use(handlers); // Use routes from handlers
}
// Start the server for development or production
public start(): void {
this.server = http.createServer(this.app);
this.server.listen(this.port);
this.server.on('error', this.onError.bind(this));
this.server.on('listening', this.onListening.bind(this));
}
// Normalize port for consistency
private normalizePort(val: string | number): number | string | false {
const port = typeof val === 'string' ? parseInt(val, 10) : val;
return isNaN(port) ? val : port >= 0 ? port : false;
}
private onError(error: NodeJS.ErrnoException): void {
if (error.syscall !== 'listen') throw error;
const bind = typeof this.port === 'string' ? `Pipe ${this.port}` : `Port ${this.port}`;
switch (error.code) {
case 'EACCES':
Logger.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
Logger.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
}
private onListening(): void {
Logger.log(`Listening on ${DRPM_REGISTRY_URL}`);
}
// Expose Express instance for external configuration if needed
public getApp(): Express {
return this.app;
}
}