You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.4 KiB
62 lines
2.4 KiB
import Module from '../Module.ts'
|
|
import Kernel from '../Kernel.ts'
|
|
import PrepareRequest from './PrepareRequest.ts'
|
|
import Routing from '../../../unit/Routing.ts'
|
|
import {Logging} from '../../../service/logging/Logging.ts'
|
|
import {Request} from '../../Request.ts'
|
|
import Config from '../../../unit/Config.ts'
|
|
import ActivatedRoute from '../../routing/ActivatedRoute.ts'
|
|
import {Injectable} from '../../../../../di/src/decorator/Injection.ts'
|
|
|
|
/**
|
|
* HTTP kernel middleware to resolve and mount the registered route onto the request.
|
|
* @extends Module
|
|
*/
|
|
@Injectable()
|
|
export default class MountActivatedRoute extends Module {
|
|
public static register(kernel: Kernel) {
|
|
kernel.register(this).after(PrepareRequest)
|
|
}
|
|
|
|
constructor(
|
|
protected readonly routing: Routing,
|
|
protected readonly config: Config,
|
|
protected readonly logger: Logging,
|
|
) {
|
|
super()
|
|
}
|
|
|
|
/**
|
|
* Parse and resolve the route and mount it into the request object.
|
|
* @param {Request} request
|
|
*/
|
|
public async apply(request: Request): Promise<Request> {
|
|
let incoming = this.routing.resolve([request.path])
|
|
this.logger.info(`${request.method} ${incoming}`)
|
|
|
|
const prefix: string | undefined = this.config.get('server.prefix')
|
|
const allow_mount_without_prefix: boolean = this.config.get('server.allow_mount_without_prefix')
|
|
|
|
if ( prefix && this.routing.resolve([prefix]) !== '/' ) {
|
|
if ( incoming.startsWith(prefix) ) {
|
|
incoming = this.routing.resolve([incoming.replace(prefix, '')])
|
|
this.logger.verbose(`Resolved prefix: ${incoming}`)
|
|
} else if ( !allow_mount_without_prefix ) {
|
|
this.logger.warn(`Will not attempt to mount route with missing prefix: ${incoming}`)
|
|
this.logger.debug('To allow this, set the config server.allow_mount_without_prefix = true.')
|
|
return request
|
|
}
|
|
}
|
|
|
|
const activated_route: ActivatedRoute | undefined = this.routing.build(incoming, request.method.toLowerCase())
|
|
if ( activated_route ) {
|
|
this.logger.verbose(`Resolved activated route: ${activated_route.route.route}`)
|
|
request.route = activated_route
|
|
} else {
|
|
this.logger.verbose(`Unable to resolve route to activated route. No matching route was found.`)
|
|
}
|
|
|
|
return request
|
|
}
|
|
}
|