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.
lib/src/http/response/ViewResponseFactory.ts

46 lines
1.5 KiB

import {Container} from '../../di'
import {ResponseFactory} from './ResponseFactory'
import {Request} from '../lifecycle/Request'
import {ViewEngine} from '../../views/ViewEngine'
/**
* Helper function that creates a new ViewResponseFactory to render the given view
* with the specified data.
* @param name
* @param data
*/
export function view(name: string, data?: {[key: string]: any}): ViewResponseFactory {
return new ViewResponseFactory(name, data)
}
/**
* Helper function that creates a new ViewResponseFactory that redirects the user to
* the given URL.
* @param url
*/
export function redirectToGet(url: string): ViewResponseFactory {
return view('@extollo:redirect', { redirectUrl: url })
}
/**
* HTTP response factory that uses the ViewEngine service to render a view
* and send it as HTML.
*/
export class ViewResponseFactory extends ResponseFactory {
constructor(
/** The name of the view to render. */
public readonly viewName: string,
/** Optional data that should be passed to the view engine as params. */
public readonly data?: {[key: string]: any},
) {
super()
}
public async write(request: Request): Promise<Request> {
const viewEngine = <ViewEngine> Container.getContainer().make(ViewEngine)
request.response.body = await viewEngine.renderByName(this.viewName, this.data || {})
request.response.setHeader('Content-Type', 'text/html; charset=utf-8')
return request
}
}