Skip to main content

Class: Server

Defined in: service-core/src/Server.ts:157

Provides an HTTP server utilizing uWebSockets.js. The server automatically registers all routes, and establishes database connections for all configured data stores. Additionally provides automatic authentication handling using JSON Web Token (JWT) directly — no Passport dependency required. When provided an OpenAPI specification object the server will also automatically serve this specification via the GET /openapi.json route.

Routes are defined by creating any class definition using the various decorators found in RouteDecorators and saving these files in the routes subfolder. Upon server start, the routes folder is scanned for any class that has been decorated with @Route and is automatically loaded and registered. Similarly, if the class is decorated with the @Model decorator the resulting route object will have the associated data model definition object injected into the constructor.

SSL termination is supported by providing an ssl configuration block with key, cert, and optionally ca and passphrase file paths. When ssl is present the server uses uWS.SSLApp().

IPv6 is supported by setting listen_host to "::" in configuration (default "0.0.0.0").

By default all registered endpoints that do not explicitly have an @Auth decorator have the JWT authentication strategy applied. This allows users to be implicitly authenticated without requiring additional configuration. Once authenticated, the provided request argument will have the user property available containing information about the authenticated user. If the user property is undefined then no user has been authenticated or the authentication attempt failed.

The following is an example of a simple route class.

import { DefaultBehaviors, RouteDecorators } from "@rapidrest/service-core";
import { Get, Route } = RouteDecorators;

@Route("/hello")
class TestRoute extends ModelRoute {
constructor(model: any) {
super(model);
}

@Get()
count(req: any, res: any, next: Function): any {
return res.send("Hello World!");
}
}

export default TestRoute;

The following is an example of a route class that is bound to a data model providing basic CRUDS operations.

import { DefaultBehaviors, ModelDecorators, ModelRoute, RouteDecorators } from "@rapidrest/service-core";
import { After, Before, Delete, Get, Post, Put, Route, Validate } = RouteDecorators;
import { Model } = ModelDecorators;
import { marshall } = DefaultBehaviors;

@Model("Item")
@Route("/items")
class ItemRoute extends ModelRoute {
constructor(model: any) {
super(model);
}

@Get()
@Before(super.count)
@After(marshall)
count(req: any, res: any, next: Function): any {
return next();
}

@Post()
@Before([super.create])
@After([this.prepare, marshall])
create(req: any, res: any, next: Function): any {
return next();
}

@Delete(":id")
@Before([super.delete])
delete(req: any, res: any, next: Function): any {
return next();
}

@Get()
@Before([super.findAll])
@After(this.prepareAndSend)
findAll(req: any, res: any, next: Function): any {
return next();
}

@Get(":id")
@Before([super.findById])
@After([this.prepare, marshall])
findById(req: any, res: any, next: Function): any {
return next();
}

@Put(":id")
@Before([super.update])
@After([this.prepare, marshall])
update(req: any, res: any, next: Function): any {
return next();
}
}

export default ItemRoute;

Constructors​

Constructor​

new Server(options): Server

Defined in: service-core/src/Server.ts:223

Creates a new instance of Server with the specified default options.

Parameters​

options​

ServerOptions

The configuration options to apply for this server.

Returns​

Server

Properties​

apiSpec?​

protected optional apiSpec?: OpenApiSpec

Defined in: service-core/src/Server.ts:159

The OpenAPI specification object to use to construct the server with.


app​

protected app: IHttpRouter

Defined in: service-core/src/Server.ts:161

The underlying HTTP router (uWS-backed on Node, Bun.serve()-backed under the Bun runtime) that provides HTTP processing services.


basePath​

protected readonly basePath: string

Defined in: service-core/src/Server.ts:163

The base file system path that will be searched for models and routes.


classLoader​

protected classLoader: ClassLoader

Defined in: service-core/src/Server.ts:169

The ClassLoader used to scan the source for all exported classes.


config?​

protected readonly optional config?: any

Defined in: service-core/src/Server.ts:165

The global object containing configuration information to use.


connectionManager?​

protected optional connectionManager?: ConnectionManager

Defined in: service-core/src/Server.ts:167

The manager for handling database connections.


eventListenerManager?​

protected optional eventListenerManager?: EventListenerManager

Defined in: service-core/src/Server.ts:171

The manager for handling events.


logger​

protected readonly logger: any

Defined in: service-core/src/Server.ts:173

The logging utility to use when outputing to console/file.


metricCompletedRequests​

protected metricCompletedRequests: Counter<string>

Defined in: service-core/src/Server.ts:205


metricFailedRequests​

protected metricFailedRequests: Counter<string>

Defined in: service-core/src/Server.ts:209


metricRequestPath​

protected metricRequestPath: Counter<string>

Defined in: service-core/src/Server.ts:189


metricRequestStatus​

protected metricRequestStatus: Counter<string>

Defined in: service-core/src/Server.ts:194


metricRequestTime​

protected metricRequestTime: Histogram<string>

Defined in: service-core/src/Server.ts:199


metricTotalRequests​

protected metricTotalRequests: Counter<string>

Defined in: service-core/src/Server.ts:213


objectFactory​

protected readonly objectFactory: ObjectFactory

Defined in: service-core/src/Server.ts:175

The object factory to use when injecting dependencies.


port​

readonly port: number

Defined in: service-core/src/Server.ts:177

The port that the server is listening on.


routeUtils?​

protected optional routeUtils?: RouteUtils

Defined in: service-core/src/Server.ts:178


serviceManager?​

protected optional serviceManager?: BackgroundServiceManager

Defined in: service-core/src/Server.ts:179


sessionManager?​

protected optional sessionManager?: SessionManager

Defined in: service-core/src/Server.ts:181

Manages cross-request session support. Only set when a session config block is present.

Methods​

getApplication()​

getApplication(): IHttpRouter

Defined in: service-core/src/Server.ts:236

Returns the HTTP router instance.

Returns​

IHttpRouter


handleError()​

protected handleError(err, _req, res, next): void

Defined in: service-core/src/Server.ts:526

The final error handling middleware. Logs the error and sends it to the client as JSON (see serializeError()).

Parameters​

err​

any

_req​

HttpRequest

res​

HttpResponse

next​

NextFunction

Returns​

void


isRunning()​

isRunning(): boolean

Defined in: service-core/src/Server.ts:243

Returns true if the server is running, otherwise false.

Returns​

boolean


postStart()​

protected postStart(): void | Promise<void>

Defined in: service-core/src/Server.ts:257

Override this function to add custom behavior after the server is started.

Returns​

void | Promise<void>


preStart()​

protected preStart(): void | Promise<void>

Defined in: service-core/src/Server.ts:250

Override this function to add custom behavior before the server is started.

Returns​

void | Promise<void>


recordRequestMetrics()​

protected recordRequestMetrics(req, res): void

Defined in: service-core/src/Server.ts:570

The final middleware of every request: records the request metrics and ends the response if nothing else did. Metrics are labeled with req.routePattern rather than the raw path, so their cardinality is bounded by the application's routes.

Parameters​

req​

HttpRequest

res​

HttpResponse

Returns​

void


restart()​

restart(): Promise<void>

Defined in: service-core/src/Server.ts:649

Restarts the HTTP listen server using the provided configuration and OpenAPI specification.

Returns​

Promise<void>


serializeError()​

protected serializeError(err): any

Defined in: service-core/src/Server.ts:507

Serializes one error for a client response. An ApiError keeps its own fields (code, status, message, ...). Anything else, such as a raw database driver error carrying the failed SQL query and its parameters, is replaced by the generic internal error so none of its details reach the client. Stack traces are never included.

Parameters​

err​

any

The error to serialize.

Returns​

any


start()​

start(): Promise<void>

Defined in: service-core/src/Server.ts:264

Starts an HTTP listen server based on the provided configuration and OpenAPI specification.

Returns​

Promise<void>


stop()​

stop(): Promise<void>

Defined in: service-core/src/Server.ts:597

Stops the server gracefully:

  1. Stops all background services.
  2. Stops accepting new connections and waits up to shutdown:drain_timeout milliseconds (default 10000) for in-flight requests to finish, then closes the remaining keep-alive and WebSocket connections.
  3. Destroys the event listener manager, closing its redis subscription.
  4. Closes all database connections.

The whole sequence is bounded by a 30 second watchdog.

Returns​

Promise<void>