Named routes & basic login framework

This commit is contained in:
2021-07-17 12:49:07 -05:00
parent e33d8dee8f
commit e86cf420df
26 changed files with 412 additions and 77 deletions

View File

@@ -0,0 +1,31 @@
import {ResponseFactory} from './ResponseFactory'
import {HTTPStatus} from '../../util'
import {Request} from '../lifecycle/Request'
/**
* Helper function to create a new RedirectResponseFactory to the given destination.
* @param destination
*/
export function redirect(destination: string): RedirectResponseFactory {
return new RedirectResponseFactory(destination)
}
/**
* Response factory that sends an HTTP redirect to the given destination.
*/
export class RedirectResponseFactory extends ResponseFactory {
protected targetStatus: HTTPStatus = HTTPStatus.MOVED_TEMPORARILY
constructor(
/** THe URL where the client should redirect to. */
public readonly destination: string,
) {
super()
}
public async write(request: Request): Promise<Request> {
request = await super.write(request)
request.response.setHeader('Location', this.destination)
return request
}
}

View File

@@ -0,0 +1,40 @@
import {ResponseFactory} from './ResponseFactory'
import {HTTPStatus} from '../../util'
import {Request} from '../lifecycle/Request'
import {Routing} from '../../service/Routing'
/**
* Helper function to create a new RouteResponseFactory to the given destination.
* @param nameOrPath
*/
export function route(nameOrPath: string): RouteResponseFactory {
return new RouteResponseFactory(nameOrPath)
}
/**
* Response factory that sends an HTTP redirect to the given destination.
*/
export class RouteResponseFactory extends ResponseFactory {
protected targetStatus: HTTPStatus = HTTPStatus.MOVED_TEMPORARILY
constructor(
/** The alias or path of the route to redirect to. */
public readonly nameOrPath: string,
) {
super()
}
public async write(request: Request): Promise<Request> {
const routing = <Routing> request.make(Routing)
request = await super.write(request)
try {
const routePath = routing.getNamedPath(this.nameOrPath)
request.response.setHeader('Location', routePath.toRemote)
} catch (e: unknown) {
request.response.setHeader('Location', routing.getAppUrl().concat(this.nameOrPath).toRemote)
}
return request
}
}

View File

@@ -6,7 +6,7 @@ import {Request} from '../lifecycle/Request'
* Helper function to create a new TemporaryRedirectResponseFactory to the given destination.
* @param destination
*/
export function redirect(destination: string): TemporaryRedirectResponseFactory {
export function temporary(destination: string): TemporaryRedirectResponseFactory {
return new TemporaryRedirectResponseFactory(destination)
}