Skip to content

Commit

Permalink
fix: ensure server is booted only once and routes are committed once
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Oct 9, 2024
1 parent 6473391 commit bad9443
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/router/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import type {
MakeSignedUrlOptions,
GetControllerHandlers,
} from '../types/route.js'
import debug from '../debug.js'
import { parseRoutePattern } from './parser.js'

/**
Expand All @@ -50,6 +51,8 @@ import { parseRoutePattern } from './parser.js'
* ```
*/
export class Router extends LookupStore {
#commited: boolean = false

/**
* Application is needed to resolve string based controller expressions
*/
Expand Down Expand Up @@ -93,6 +96,15 @@ export class Router extends LookupStore {
*/
matchers = new Matchers()

/**
* Check if routes have been committed to the store. Once
* routes are committed, defining new set of routes will
* have no impact
*/
get commited() {
return this.#commited
}

constructor(app: Application<any>, encryption: Encryption, qsParser: Qs) {
super(encryption, qsParser)
this.#app = app
Expand Down Expand Up @@ -328,6 +340,11 @@ export class Router extends LookupStore {
* commit method is called.
*/
commit() {
if (this.#commited) {
return
}

debug('Committing routes to the routes store')
const routeNamesByDomain: Map<string, Set<string>> = new Map()

toRoutesJSON(this.routes).forEach((route) => {
Expand Down Expand Up @@ -367,6 +384,7 @@ export class Router extends LookupStore {
this.routes = []
this.#globalMatchers = {}
this.#middleware = []
this.#commited = true
}

/**
Expand Down
15 changes: 15 additions & 0 deletions src/server/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ import { middlewareHandler } from './factories/middleware_handler.js'
* registered routes.
*/
export class Server {
#booted: boolean = false

/**
* The default error handler to use
*/
Expand Down Expand Up @@ -129,6 +131,13 @@ export class Server {
return this.#resolvedErrorHandler.handle(error, ctx)
}

/**
* Check if the server has already been booted
*/
get booted() {
return this.#booted
}

/**
* Know if async local storage is enabled or not.
*/
Expand Down Expand Up @@ -250,6 +259,10 @@ export class Server {
* - Resolve and construct the error handler.
*/
async boot() {
if (this.#booted) {
return
}

debug('booting HTTP server')

/**
Expand All @@ -273,6 +286,8 @@ export class Server {
const moduleExports = await this.#errorHandler()
this.#resolvedErrorHandler = await this.#app.container.make(moduleExports.default)
}

this.#booted = true
}

/**
Expand Down

0 comments on commit bad9443

Please sign in to comment.