lib/src/http/response/ViewResponseFactory.ts

37 lines
1.2 KiB
TypeScript
Raw Normal View History

2021-06-03 03:36:25 +00:00
import {Container} from '../../di'
import {ResponseFactory} from './ResponseFactory'
import {Request} from '../lifecycle/Request'
import {ViewEngine} from '../../views/ViewEngine'
2021-03-09 00:07:55 +00:00
2021-03-25 13:50:13 +00:00
/**
* Helper function that creates a new ViewResponseFactory to render the given view
* with the specified data.
* @param name
* @param data
*/
2021-03-09 00:07:55 +00:00
export function view(name: string, data?: {[key: string]: any}): ViewResponseFactory {
return new ViewResponseFactory(name, data)
}
2021-03-25 13:50:13 +00:00
/**
* HTTP response factory that uses the ViewEngine service to render a view
* and send it as HTML.
*/
2021-03-09 00:07:55 +00:00
export class ViewResponseFactory extends ResponseFactory {
constructor(
2021-03-25 13:50:13 +00:00
/** The name of the view to render. */
2021-03-09 00:07:55 +00:00
public readonly viewName: string,
2021-03-25 13:50:13 +00:00
/** Optional data that should be passed to the view engine as params. */
2021-06-03 03:36:25 +00:00
public readonly data?: {[key: string]: any},
) {
super()
}
2021-03-09 00:07:55 +00:00
2021-06-03 03:36:25 +00:00
public async write(request: Request): Promise<Request> {
2021-03-09 00:07:55 +00:00
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
}
}