视图的职责是基于模型渲染真正的内容响应给客户端,同时还需要告诉浏览器内容类型 content-type。

定义

  1. export interface View {
  2. readonly contentType: string;
  3. render(model: any): Promise<void>;
  4. support(viewName: string): Promise<boolean>;
  5. }

实现

  1. @Component(View)
  2. export class JsonView implements View {
  3. static VIEW_NAME = 'json';
  4. readonly contentType = 'application/json';
  5. readonly priority = 500;
  6. async render(model: any): Promise<void> {
  7. const response = Context.getCurrent().response;
  8. response.body = JSON.stringify(model);
  9. }
  10. support(viewName: string): Promise<boolean> {
  11. return Promise.resolve(viewName === JsonView.VIEW_NAME);
  12. }
  13. }

使用

  1. @Controller('users')
  2. export class UserController {
  3. @Get(':id')
  4. @View(JsonView.VIEW_NAME)
  5. get(@Param() id: string) {
  6. ...
  7. }
  8. }