parent
338b9be506
commit
3acc1bc83e
@ -0,0 +1,33 @@
|
||||
import {Injectable, Inject} from "@extollo/di"
|
||||
import {HTTPKernelModule} from "../HTTPKernelModule";
|
||||
import {HTTPKernel} from "../HTTPKernel";
|
||||
import {Request} from "../../lifecycle/Request";
|
||||
import {Routing} from "../../../service/Routing";
|
||||
import {ActivatedRoute} from "../../routing/ActivatedRoute";
|
||||
import {Logging} from "../../../service/Logging";
|
||||
|
||||
@Injectable()
|
||||
export class MountActivatedRouteHTTPModule extends HTTPKernelModule {
|
||||
@Inject()
|
||||
protected readonly routing!: Routing
|
||||
|
||||
@Inject()
|
||||
protected readonly logging!: Logging
|
||||
|
||||
public static register(kernel: HTTPKernel) {
|
||||
kernel.register(this).before()
|
||||
}
|
||||
|
||||
public async apply(request: Request): Promise<Request> {
|
||||
const route = this.routing.match(request.method, request.path)
|
||||
if ( route ) {
|
||||
this.logging.verbose(`Mounting activated route: ${request.path} -> ${route}`)
|
||||
const activated = new ActivatedRoute(route, request.path)
|
||||
request.registerSingletonInstance<ActivatedRoute>(ActivatedRoute, activated)
|
||||
} else {
|
||||
this.logging.debug(`No matching route found for: ${request.method} -> ${request.path}`)
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
@ -1,17 +1,23 @@
|
||||
import {HTTPKernelModule} from "../HTTPKernelModule";
|
||||
import {Request} from "../../lifecycle/Request";
|
||||
import {Injectable} from "@extollo/di"
|
||||
import {Injectable, Inject} from "@extollo/di"
|
||||
import {HTTPKernel} from "../HTTPKernel";
|
||||
import {Config} from "../../../service/Config";
|
||||
|
||||
@Injectable()
|
||||
export class PoweredByHeaderInjectionHTTPModule extends HTTPKernelModule {
|
||||
@Inject()
|
||||
protected readonly config!: Config;
|
||||
|
||||
public static register(kernel: HTTPKernel) {
|
||||
kernel.register(this).after()
|
||||
}
|
||||
|
||||
public async apply(request: Request) {
|
||||
// FIXME make this configurable
|
||||
request.response.setHeader('X-Powered-By', 'Extollo')
|
||||
if ( !this.config.get('server.poweredBy.hide', false) ) {
|
||||
request.response.setHeader('X-Powered-By', this.config.get('server.poweredBy.header', 'Extollo'))
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,23 @@
|
||||
import {ErrorWithContext} from "@extollo/util";
|
||||
import {Route} from "./Route";
|
||||
|
||||
export class ActivatedRoute {
|
||||
public readonly params: {[key: string]: string}
|
||||
|
||||
constructor(
|
||||
public readonly route: Route,
|
||||
public readonly path: string
|
||||
) {
|
||||
const params = route.extract(path)
|
||||
if ( !params ) {
|
||||
const error = new ErrorWithContext('Cannot get params for route. Path does not match.')
|
||||
error.context = {
|
||||
matchedRoute: String(route),
|
||||
requestPath: path,
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
this.params = params
|
||||
}
|
||||
}
|
@ -0,0 +1,141 @@
|
||||
import {AppClass} from "../../lifecycle/AppClass";
|
||||
import {HTTPMethod, Request} from "../lifecycle/Request";
|
||||
import {Application} from "../../lifecycle/Application";
|
||||
import {RouteGroup} from "./RouteGroup";
|
||||
|
||||
export type RouteHandler = (request: Request) => void | Promise<void> // FIXME want to do some improvements here
|
||||
|
||||
// TODO middleware, domains, named routes - support this on groups as well
|
||||
|
||||
export class Route extends AppClass {
|
||||
private static registeredRoutes: Route[] = []
|
||||
private static registeredGroups: RouteGroup[] = []
|
||||
|
||||
private static compiledGroupStack: RouteGroup[] = []
|
||||
|
||||
public static registerGroup(group: RouteGroup) {
|
||||
this.registeredGroups.push(group)
|
||||
}
|
||||
|
||||
public static async compile(): Promise<Route[]> {
|
||||
let registeredRoutes = this.registeredRoutes
|
||||
const registeredGroups = this.registeredGroups
|
||||
|
||||
this.registeredRoutes = []
|
||||
this.registeredGroups = []
|
||||
|
||||
const stack = [...this.compiledGroupStack].reverse()
|
||||
for ( const route of registeredRoutes ) {
|
||||
for ( const group of stack ) {
|
||||
route.prepend(group.prefix)
|
||||
}
|
||||
}
|
||||
|
||||
for ( const group of registeredGroups ) {
|
||||
this.compiledGroupStack.push(group)
|
||||
await group.group()
|
||||
|
||||
const childCompilation = await this.compile()
|
||||
registeredRoutes = registeredRoutes.concat(childCompilation)
|
||||
|
||||
this.compiledGroupStack.pop()
|
||||
}
|
||||
|
||||
return registeredRoutes
|
||||
}
|
||||
|
||||
public static endpoint(method: HTTPMethod | HTTPMethod[], definition: string, handler: RouteHandler) {
|
||||
const route = new Route(method, handler, definition)
|
||||
this.registeredRoutes.push(route)
|
||||
return route
|
||||
}
|
||||
|
||||
public static get(definition: string, handler: RouteHandler) {
|
||||
return this.endpoint('get', definition, handler)
|
||||
}
|
||||
|
||||
public static post(definition: string, handler: RouteHandler) {
|
||||
return this.endpoint('post', definition, handler)
|
||||
}
|
||||
|
||||
public static put(definition: string, handler: RouteHandler) {
|
||||
return this.endpoint('put', definition, handler)
|
||||
}
|
||||
|
||||
public static patch(definition: string, handler: RouteHandler) {
|
||||
return this.endpoint('patch', definition, handler)
|
||||
}
|
||||
|
||||
public static delete(definition: string, handler: RouteHandler) {
|
||||
return this.endpoint('delete', definition, handler)
|
||||
}
|
||||
|
||||
public static any(definition: string, handler: RouteHandler) {
|
||||
return this.endpoint(['get', 'put', 'patch', 'post', 'delete'], definition, handler)
|
||||
}
|
||||
|
||||
public static group(prefix: string, group: () => void | Promise<void>) {
|
||||
const grp = <RouteGroup> Application.getApplication().make(RouteGroup, group, prefix)
|
||||
this.registeredGroups.push(grp)
|
||||
return grp
|
||||
}
|
||||
|
||||
constructor(
|
||||
protected method: HTTPMethod | HTTPMethod[],
|
||||
protected handler: RouteHandler,
|
||||
protected route: string
|
||||
) { super() }
|
||||
|
||||
public match(method: HTTPMethod, potential: string): boolean {
|
||||
if ( Array.isArray(this.method) && !this.method.includes(method) ) return false
|
||||
else if ( !Array.isArray(this.method) && this.method !== method ) return false
|
||||
|
||||
return !!this.extract(potential)
|
||||
}
|
||||
|
||||
public extract(potential: string): {[key: string]: string} | undefined {
|
||||
const routeParts = (this.route.startsWith('/') ? this.route.substr(1) : this.route).split('/')
|
||||
const potentialParts = (potential.startsWith('/') ? potential.substr(1) : potential).split('/')
|
||||
|
||||
const params: any = {}
|
||||
let wildcardIdx = 0
|
||||
|
||||
for ( let i = 0; i < routeParts.length; i += 1 ) {
|
||||
const part = routeParts[i]
|
||||
|
||||
if ( part === '**' ) {
|
||||
params[wildcardIdx] = potentialParts.slice(i).join('/')
|
||||
return params
|
||||
}
|
||||
|
||||
if ( (potentialParts.length - 1) < i ) {
|
||||
return
|
||||
}
|
||||
|
||||
if ( part === '*' ) {
|
||||
params[wildcardIdx] = potentialParts[i]
|
||||
wildcardIdx += 1
|
||||
} else if ( part.startsWith(':') ) {
|
||||
params[part.substr(1)] = potentialParts[i]
|
||||
} else if ( potentialParts[i] !== part ) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// If we got here, we didn't find a **
|
||||
// So, if the lengths are different, fail
|
||||
if ( routeParts.length !== potentialParts.length ) return
|
||||
return params
|
||||
}
|
||||
|
||||
private prepend(prefix: string) {
|
||||
if ( !prefix.endsWith('/') ) prefix = `${prefix}/`
|
||||
if ( this.route.startsWith('/') ) this.route = this.route.substring(1)
|
||||
this.route = `${prefix}${this.route}`
|
||||
}
|
||||
|
||||
toString() {
|
||||
const method = Array.isArray(this.method) ? this.method : [this.method]
|
||||
return `${method.join('|')} -> ${this.route}`
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
import {AppClass} from "../../lifecycle/AppClass";
|
||||
|
||||
export class RouteGroup extends AppClass {
|
||||
private static currentGroupNesting: RouteGroup[] = []
|
||||
|
||||
public static getCurrentGroupHierarchy(): RouteGroup[] {
|
||||
return [...this.currentGroupNesting]
|
||||
}
|
||||
|
||||
constructor(
|
||||
public readonly group: () => void | Promise<void>,
|
||||
public readonly prefix: string
|
||||
) { super() }
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
import {Singleton, Inject} from "@extollo/di"
|
||||
import {UniversalPath, Collection} from "@extollo/util"
|
||||
import {Unit} from "../lifecycle/Unit"
|
||||
import {Logging} from "./Logging"
|
||||
import {Route} from "../http/routing/Route";
|
||||
import {HTTPMethod} from "../http/lifecycle/Request";
|
||||
|
||||
@Singleton()
|
||||
export class Routing extends Unit {
|
||||
@Inject()
|
||||
protected readonly logging!: Logging
|
||||
|
||||
protected compiledRoutes: Collection<Route> = new Collection<Route>()
|
||||
|
||||
public async up() {
|
||||
for await ( const entry of this.path.walk() ) {
|
||||
if ( !entry.endsWith('.routes.js') ) {
|
||||
this.logging.debug(`Skipping routes file with invalid suffix: ${entry}`)
|
||||
continue
|
||||
}
|
||||
|
||||
this.logging.info(`Importing routes from: ${entry}`)
|
||||
await import(entry)
|
||||
}
|
||||
|
||||
this.logging.info('Compiling routes...')
|
||||
this.compiledRoutes = new Collection<Route>(await Route.compile())
|
||||
|
||||
this.logging.info(`Compiled ${this.compiledRoutes.length} route(s).`)
|
||||
this.compiledRoutes.each(route => {
|
||||
this.logging.verbose(`${route}`)
|
||||
})
|
||||
}
|
||||
|
||||
public match(method: HTTPMethod, path: string): Route | undefined {
|
||||
return this.compiledRoutes.firstWhere(route => {
|
||||
return route.match(method, path)
|
||||
})
|
||||
}
|
||||
|
||||
public get path(): UniversalPath {
|
||||
return this.app().appPath('http', 'routes')
|
||||
}
|
||||
}
|
Loading…
Reference in new issue