41 lines
1.2 KiB
TypeScript
41 lines
1.2 KiB
TypeScript
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
|
|
}
|
|
}
|