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
The configuration options to apply for this server.
Returns
Server
Properties
apiSpec?
protectedoptionalapiSpec?:OpenApiSpec
Defined in: service-core/src/Server.ts:159
The OpenAPI specification object to use to construct the server with.
app
protectedapp: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
protectedreadonlybasePath:string
Defined in: service-core/src/Server.ts:163
The base file system path that will be searched for models and routes.
classLoader
protectedclassLoader:ClassLoader
Defined in: service-core/src/Server.ts:169
The ClassLoader used to scan the source for all exported classes.
config?
protectedreadonlyoptionalconfig?:any
Defined in: service-core/src/Server.ts:165
The global object containing configuration information to use.
connectionManager?
protectedoptionalconnectionManager?:ConnectionManager
Defined in: service-core/src/Server.ts:167
The manager for handling database connections.
eventListenerManager?
protectedoptionaleventListenerManager?:EventListenerManager
Defined in: service-core/src/Server.ts:171
The manager for handling events.
logger
protectedreadonlylogger:any
Defined in: service-core/src/Server.ts:173
The logging utility to use when outputing to console/file.
metricCompletedRequests
protectedmetricCompletedRequests:Counter<string>
Defined in: service-core/src/Server.ts:205
metricFailedRequests
protectedmetricFailedRequests:Counter<string>
Defined in: service-core/src/Server.ts:209
metricRequestPath
protectedmetricRequestPath:Counter<string>
Defined in: service-core/src/Server.ts:189
metricRequestStatus
protectedmetricRequestStatus:Counter<string>
Defined in: service-core/src/Server.ts:194
metricRequestTime
protectedmetricRequestTime:Histogram<string>
Defined in: service-core/src/Server.ts:199
metricTotalRequests
protectedmetricTotalRequests:Counter<string>
Defined in: service-core/src/Server.ts:213
objectFactory
protectedreadonlyobjectFactory:ObjectFactory
Defined in: service-core/src/Server.ts:175
The object factory to use when injecting dependencies.
port
readonlyport:number
Defined in: service-core/src/Server.ts:177
The port that the server is listening on.
routeUtils?
protectedoptionalrouteUtils?:RouteUtils
Defined in: service-core/src/Server.ts:178
serviceManager?
protectedoptionalserviceManager?:BackgroundServiceManager
Defined in: service-core/src/Server.ts:179
sessionManager?
protectedoptionalsessionManager?: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
handleError()
protectedhandleError(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
res
next
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()
protectedpostStart():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()
protectedpreStart():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()
protectedrecordRequestMetrics(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
res
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()
protectedserializeError(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:
- Stops all background services.
- Stops accepting new connections and waits up to
shutdown:drain_timeoutmilliseconds (default 10000) for in-flight requests to finish, then closes the remaining keep-alive and WebSocket connections. - Destroys the event listener manager, closing its redis subscription.
- Closes all database connections.
The whole sequence is bounded by a 30 second watchdog.
Returns
Promise<void>